Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Check if all n numbers are present in a list

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!

like image 919
ProgrammingNoob Avatar asked Mar 15 '23 19:03

ProgrammingNoob


2 Answers

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
like image 56
Mazdak Avatar answered Mar 31 '23 19:03

Mazdak


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)))
like image 22
user4549992 Avatar answered Mar 31 '23 19:03

user4549992