String contains all the elements of a list

前端 未结 5 1027
暖寄归人
暖寄归人 2021-01-05 18:32

I am shifting to Python, and am still relatively new to the pythonic approach. I want to write a function that takes a string and a list and returns true if all the elements

5条回答
  •  长情又很酷
    2021-01-05 18:42

    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:

    • all function

    • set complexity

提交回复
热议问题