[英]Test for consecutive numbers in list
我有一個僅包含整數的列表,我想檢查列表中的所有數字是否連續(數字的順序無關緊要)。
如果存在重復的元素,則函數應返回False。
這是我嘗試解決的問題:
def isconsecutive(lst):
"""
Returns True if all numbers in lst can be ordered consecutively, and False otherwise
"""
if len(set(lst)) == len(lst) and max(lst) - min(lst) == len(lst) - 1:
return True
else:
return False
例如:
l = [-2,-3,-1,0,1,3,2,5,4]
print(isconsecutive(l))
True
這是最好的方法嗎?
這是另一種解決方案:
def is_consecutive(l):
setl = set(l)
return len(l) == len(setl) and setl == set(range(min(l), max(l)+1))
但是,您的解決方案可能更好,因為您沒有將整個范圍存儲在內存中。
請注意,您始終可以簡化
if boolean_expression:
return True
else:
return False
通過
return boolean_expression
關於查看元素多少次的一種更好的方法是在一次通過中結合找到所有重復對象的最小 , 最大和短路 ,盡管取決於輸入的內置函數的速度可能會擊敗它。 :
def mn_mx(l):
mn, mx = float("inf"), float("-inf")
seen = set()
for ele in l:
# if we already saw the ele, end the function
if ele in seen:
return False, False
if ele < mn:
mn = ele
if ele > mx:
mx = ele
seen.add(ele)
return mn, mx
def isconsecutive(lst):
"""
Returns True if all numbers in lst can be ordered consecutively, and False otherwise
"""
mn, mx = mn_mx(lst)
# could check either, if mn is False we found a dupe
if mn is False:
return False
# if we get here there are no dupes
return mx - mn == len(lst) - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.