The Python Oracle

String contains all the elements of a list

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 String Contains All The Elements Of A List
00:45 Accepted Answer Score 22
00:53 Answer 2 Score 3
01:12 Answer 3 Score 3
01:41 Answer 4 Score 2
01:58 Thank you

--

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

--

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)