With sorting
In Python 3, I use this simple solution:
def check(lst):
lst = sorted(lst)
if lst:
return lst == list(range(lst[0], lst[-1] + 1))
else:
return True
Note that, after sorting the list, its minimum and maximum come for free as the first (lst[0]
) and the last (lst[-1]
) elements.
I'm returning True
in case the argument is empty, but this decision is arbitrary. Choose whatever fits best your use case.
In this solution, we first sort the argument and then compare it with another list that we know that is consecutive and has no repetitions.
Without sorting
In one of the answers, the OP commented asking if it would be possible to do the same without sorting the list. This is interesting, and this is my solution:
def check(lst):
if lst:
r = range(min(lst), max(lst) + 1) # *r* is our reference
return (
len(lst) == len(r)
and all(map(lst.__contains__, r))
# alternative: all(x in lst for x in r)
# test if every element of the reference *r* is in *lst*
)
else:
return True
In this solution, we build a reference range r
that is a consecutive (and thus non-repeating) sequence of int
s. With this, our test is simple: first we check that lst
has the correct number of elements (not more, which would indicate repetitions, nor less, which indicates gaps) by comparing it with the reference. Then we check that every element in our reference is also in lst
(this is what all(map(lst.__contains__, r))
is doing: it iterates over r
and tests if all of its elements are in lts
).
True
, 5 and 2 are not consecutiveany(diff(sort(x)) == 1) & all(table(x) == 1)
but I don't know Python yet, so I'm interested in seeing how it would be done. I'm trying to translate wherever possible to learn both.[1,2,2,3]
? Please reword the question if the answer isTrue