String contains all the elements of a list

前端 未结 5 896
暖寄归人
暖寄归人 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

    0 讨论(0)
  • 2021-01-05 18:49
    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 :)

    0 讨论(0)
  • 2021-01-05 18:50

    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)
    
    0 讨论(0)
  • 2021-01-05 19:03

    For fun, I thought I'd do it with iterators and map:

    from operator import contains
    from itertools import imap, repeat
    
    def myfun(str, list):
        return all(imap(contains, repeat(str), list))
    

    Then I realised that this essentially does the same thing as the accepted answer, but probably with more method calls.

    def myfun(str, list):
        return all(letter in str for letter in list)
    
    0 讨论(0)
  • 2021-01-05 19:05
    >>> all(x in 'tomato' for x in ['t','o','m','a'])
    True
    >>> all(x in 'potato' for x in ['t','o','m','a'])
    False
    
    0 讨论(0)
提交回复
热议问题