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
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
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 :)
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)
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)
>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False