Ellie Paul
Ellie Paul

Reputation: 41

Finding a letter in a list

I have a problem that states: Write a function that takes, as an argument, a list and a string,and returns a Boolean based on whether or not all of the letters in the string appear somewhere in the list. Here is what I have so far.

def findLetters(myList, myString):
    for letter in myString:
        if letter in myList:
            return True
    return False

Upvotes: 0

Views: 14588

Answers (3)

Here's a basic solution that's closer to what you've started:

def findLetters(myList, myString):
    found_all = False
    for s in myString:        # check each letter in the string
        if s in myList:       # see if it is in the list
            found_all = True  # keep going if found
        else:
            found_all = False # otherwise set `found` to False 
            break             # and break out of the loop

    return found_all          # return the result

result = findLetters(['a', 'l', 'i', 's', 't'], 'mlist')

# 'm' is not in the list
print result # False 

# all letters in the string are in the list; 
# ignores any extra characters in the list that are not in the string
result = findLetters(['a', 'l', 'i', 's', 't', 'p'], 'alist')

print result # True 

Upvotes: 1

Skycc
Skycc

Reputation: 3555

you are returning True if any letter match in myString, not all letter in myString. You could do the other way around, if any letter not match in myString, return False

def findLetters(myList, myString):
    for letter in myString:
        if letter not in myList:
            return False
    return True

OR use builtin function all

def findLetters(myList, myString):
  return all(letter in myList for letter in myString)

Upvotes: 0

Clayton A. Alves
Clayton A. Alves

Reputation: 408

You can map all letters using a lambda which creates a list of boolean values for all letters in my_string.

The function all returns true if all values in the l list ar True.

def find_letters(my_list, my_string): 
    l = map(lambda x: x in my_list, my_string)
    return all(l)

print(find_letters(['a', 'b', 'c'], 'cab'))

Upvotes: 0

Related Questions