Home > Software engineering >  Python function that searches through three lists of strings for an element
Python function that searches through three lists of strings for an element

Time:10-28

I need to write a function that takes three dishes and a specified ingredient and outputs true if all the dishes are free from that ingredient and false if ANY of them contain it. The inputs are the menu which is three lists of strings and the specified ingredient. I thought I had done it correctly until i went to test and got a failure. I cannot understand why?

I defined my function follows -

def free_from(test_menu:str, specified_ingredient: str):
    if specified_ingredient in test_menu:
        return(False)
    else:
        return(True)

The test that failed is as follows

test_menu = [ ['soup'],
              ['cheese'],
              ['water'] ]
expected_result = False
if free_from(test_menu, 'water') == expected_result:
#adjust the function call if necessary to match your implementation
    print('Working')
else:
    print('Failure')

The output i get is 'Failure'

CodePudding user response:

Multiple errors are in your code:

  • The return syntax is wrong, it should be return True
  • If any of the dishes does not have the ingredient, it will return False immediately, without checking the other dishes
  • The logic in the method can not make correct check, see below

You're iterating over a list of lists, so the comparison you are doing is basically 'water' in [['soup'], ['cheese'], ['water']], which can only return false (because water is not ['water']). So I would rewrite your function as follow:

def free_from(test_menu:str, specified_ingredient: str):
    for dish in test_menu:
        if specified_ingredient in test_menu:
            return False
    return True

Edit: also, your comment is not indented correctly after your condition

CodePudding user response:

You can use all, combined with generator comprehension:

test_menu = [['soup', 'watermelon'],
              ['cheese', 'tire'],
              ['water', 'chalk']]

def free_from(lst_menu, specified_ingredient):
    return all(specified_ingredient not in menu for menu in lst_menu)

print(free_from(test_menu, 'water')) # False
print(free_from(test_menu, 'melon')) # True
print(free_from(test_menu, 'meteorite')) # True

CodePudding user response:

Thanks for asking question.You need to specify not in if

def free_from(test_menu:str, specified_ingredient: str):
    if specified_ingredient not in test_menu:  ### You need to specify not 
        return False 
    else:
        return True

test_menu = [ ['soup'],
              ['cheese'],
              ['water'] ]
expected_result = False
print(free_from(test_menu, 'water'))
if free_from(test_menu, 'water') == expected_result:
#adjust the function call if necessary to match your implementation
    print('Working')
else:
    print('Failure')
  • Related