The string contains all the items in the list.

I am moving on 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 in the list are found in the string.


It seemed pretty simple. However, I come across this. The code looks something like this:


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

 Example : myfun('tomato',['t','o','m','a']) should return true myfun('potato',['t','o','m','a']) should return false myfun('tomato',['t','o','m']) should return true 

Also, I was hoping someone could suggest a possible regex approach here. I'm also trying to trick them.

+4
source share
5 answers
 >>> all(x in 'tomato' for x in ['t','o','m','a']) True >>> all(x in 'potato' for x in ['t','o','m','a']) False 
+12
source
 def myfun(str,list): for a in list: if not a in str: return False return True 

return true should be outside the for loop, and not just after the if statement, otherwise it will return true immediately after checking the first letter. this solves the problem with the code :)

+3
source

For each letter, you are viewing a list. Therefore, if the list has a length n and you have m letters, then the complexity is O(n*m) . And you can achieve O(m) if you preproject a 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 is not recommended to rename variables like str and list , as if you needed to create list later or use str , they will be obscured by your variables.

Some relevant information:

+2
source

If you do not care about repeated characters, then:

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

And, untested, if you care about duplicate characters, then perhaps (untested):

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

For fun, I thought I would do it with iterators and maps:

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

Then I realized that this essentially does the same as the accepted answer, but probably with a lot of method calls.

 def myfun(str, list): return all(letter in str for letter in list) 
0
source

Source: https://habr.com/ru/post/1268961/


All Articles