2016-10-17 67 views
2

我有一个只包含整数的列表,我想检查列表中的所有数字是否连续(数字的顺序无关紧要)。测试列表中的连续数字

如果有重复的元素,该函数应该返回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 

这是做到这一点的最好方法是什么?

+0

您的示例列表不是连续的 - 它可以重新排序为连续的整数,是什么意思?我们可以重新排列名单吗? –

+1

@DanielleM。顺序没关系 – MMF

+0

看起来很好,但你应该删除if并只是返回整个表达式 –

回答

4

这里是另一种解决方案:

def is_consecutive(l): 
    setl = set(l) 
    return len(l) == len(setl) and setl == set(range(min(l), max(l)+1)) 

然而,您的解决方案可能是更好,因为你不存储在内存中的整个范围。

请注意,您可以随时通过

return boolean_expression 
+0

不错的Julien;) – MMF

+0

我会补充一点,只要'test'是一个布尔值,'return test'是相等的,否则你将不得不打电话给'bool' –

+0

@FranciscoCouzo,这是真的,我只是做了一个编辑。 –

1

在你看多少次在元素方面更好的方法简化

if boolean_expression: 
    return True 
else: 
    return False 

将纳入找到分钟最大短路任何重复都在一个过程中,虽然可能会被内置函数的速度击败ons取决于输入:

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