Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String contains all the elements of a list

Tags:

python

regex

list

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 in the list occur in the string.


This seemed fairly simple. However, I am facing some difficulties with it. The code goes 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 if someone could suggest a possible regex approach here. I am trying out my hands on them too.

like image 766
OneMoreError Avatar asked Oct 21 '12 16:10

OneMoreError


2 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
like image 113
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 10:10

Ignacio Vazquez-Abrams


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 :)

like image 25
Samuele Mattiuzzo Avatar answered Oct 06 '22 11:10

Samuele Mattiuzzo