简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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