I want to check if my list contains all the numbers from 0 to the maximum number of the list
For ex this list contains all the numbers from 0 to 7:
l = [0,2,1,7,6,5,4,3]
but this list doesn't as it doesnt have 4 -
l = [0,2,1,6,5,7,3]
I try using zip:
all(x==y+1 for x, y in zip(sorted(l[1:]), sorted(l)))
but this doesnt work..
FOR EXAMPLE -
l = [0,3,2,5]
doesnt have 1 and 4 so it should return false!
where as -
l = [0,2,3,1,4,5]
has all the numbers from 0 to 5 so it should return true!
There is no need to use zip
with multiple zip
function.You can use sorted
:
if sorted(l)==list(range(max(l)+1))
example :
>>> sorted(l)==list(range(max(l)+1))
False
>>> l= [0,2,1,7,6,5,4,3]
>>> sorted(l)==list(range(max(l)+1))
True
Slow and dirty solition:
def f(myList):
ll = [i for i in range(max(myList))]
diff = set(ll).difference(set(myList))
if diff: return (False, diff)
return (True, "sequence without blanks")
#lets test:
t1,t2 = [0,1,7,4,5,2],[3,5,4,2,1,0]
print(map(f,(t1,t2)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With