Python 测试列表中的连续数字
我有一个只包含整数的列表,我想检查列表中的所有数字是否都是连续的(数字的顺序无关紧要) 如果有重复的元素,函数应该返回False 以下是我试图解决的问题:Python 测试列表中的连续数字,python,list,python-3.x,Python,List,Python 3.x,我有一个只包含整数的列表,我想检查列表中的所有数字是否都是连续的(数字的顺序无关紧要) 如果有重复的元素,函数应该返回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(l
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
借
就查看元素的次数而言,更好的方法是在一个过程中找到任何重复上的最小值、最大值和短路,尽管可能会被内置函数的速度击败,这取决于输入:
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
def mn_mx(l):
mn,mx=float(“inf”),float(“inf”)
seen=set()
对于l中的ele:
#如果我们已经看到ele,请结束函数
如果看到ele,则:
返回False,False
如果elemx:
mx=ele
见。添加(ele)
返回mn,mx
def是连续的(lst):
"""
如果lst中的所有数字可以连续排序,则返回True,否则返回False
"""
mn,mx=mn_mx(lst)
#可以检查其中一个,如果mn为假,我们会发现一个复制品
如果mn为假:
返回错误
#如果我们到了这里,就不会有傻瓜了
返回mx-mn==len(lst)-1
您的示例列表不是连续的-它可以重新排序为连续整数,这是您的意思吗?我们可以重新订购这个单子吗?@DanielleM。顺序并不重要关于重复元素的内容是什么?@Vermillion,那么您自己的解决方案实际上可能是最好的。实际上,这是最好的,因为你使用的是简单的数学。max(lst)-min(lst)==len(lst)-1
比创建一个集来测试同样的东西要快得多,而且节省空间。此外,此问答可能最适合于代码审查我想补充一点,返回测试
是相等的,只要测试
是一个布尔值,否则你将不得不调用bool
@FranciscoCouzo,不是真的,如果[]
如果{}
等都将计算为False,就像如果[1]
或者{1:2}
将计算为True一样。@JulienSpronck,您需要添加一个检查,确保集合的长度等于l的长度,以捕获重复的元素,否则您将得到误报。是否必须调用set(l)
两次?
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