简体   繁体   English

测试列表中的连续数字

[英]Test for consecutive numbers in list

I have a list that contains only integers, and I want to check if all the numbers in the list are consecutive (the order of the numbers does not matter). 我有一个仅包含整数的列表,我想检查列表中的所有数字是否连续(数字的顺序无关紧要)。

If there are repeated elements, the function should return False. 如果存在重复的元素,则函数应返回False。

Here is my attempt to solve this: 这是我尝试解决的问题:

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

For example: 例如:

l = [-2,-3,-1,0,1,3,2,5,4]

print(isconsecutive(l))

True

Is this the best way to do this? 这是最好的方法吗?

Here is another solution: 这是另一种解决方案:

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

However, your solution is probably better as you don't store the whole range in memory. 但是,您的解决方案可能更好,因为您没有将整个范围存储在内存中。

Note that you can always simplify 请注意,您始终可以简化

if boolean_expression:
    return True
else:
    return False

by 通过

return boolean_expression

A better approach in terms of how many times you look at the elements would be to incorporate finding the min , max and short circuiting on any dupe all in one pass, although would probably be beaten by the speed of the builtin functions depending on the inputs: 关于查看元素多少次的一种更好的方法是在一次通过中结合找到所有重复对象的最小最大短路 ,尽管取决于输入的内置函数的速度可能会击败它。 :

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM