The Python Oracle

String contains all the elements of a list

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 Question
01:13 Accepted answer (Score 18)
01:25 Answer 2 (Score 3)
02:12 Answer 3 (Score 3)
02:35 Answer 4 (Score 2)
02:58 Thank you

--

Full question
https://stackoverflow.com/questions/1299...

Answer 1 links:
[all]: http://docs.python.org/library/functions...
[set]: http://wiki.python.org/moin/TimeComplexi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #regex #list

#avk47



ACCEPTED ANSWER

Score 22


>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False



ANSWER 2

Score 3


def myfun(str,list):
   for a in list:
      if not a in str:
         return False
   return True

return true must be outside the for loop, not just after the if statement, otherwise it will return true just after the first letter has been checked. this solves your code's problem :)




ANSWER 3

Score 3


For each letter you go through the list. So if the list is of length n and you have m letters, then complexity is O(n*m). And you may achieve O(m) if you preprocess the word.

def myfun(word,L):
    word_letters = set(word) #This makes the lookup `O(1)` instead of `O(n)`
    return all(letter in word_letters for letter in L)

Also, it's not a good practice to name variables as str and list as if you will need later to create list or use str, they will be shaded by your variables.

Some relevant information:




ANSWER 4

Score 2


If you're not worried about repeat characters, then:

def myfunc(string, seq):
    return set(seq).issubset(string)

And, untested, if you do care about repeated characters, then maybe (untested):

from collections import Counter
def myfunc(string, seq):
    c1 = Counter(string)
    c2 = Counter(seq)
    return not (c2 - c1)