Vermillion - 1 year ago 96

Python Question

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?

Answer Source

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
```