I have to write a function that takes three dishes and an ingredient and outputs true if the ingredient isn't in the dish and false if any of the dishes contain the ingredient.
I've been trying this for hours and initially was having an issue where it was either outputting true or false for all test cases regardless. I have now tried using any() but its returning a TypeError: 'bool' object is not iterable and I'm getting really confused and frustrated.
any advice would be much appreciated.
def free_from(menu: list, ingredient: str):
"""Return whether ingredient is in dish.
Preconditions: menu = dish1, dish2, dish3
Postconditions: if menu has ingredient = false else true
"""
for dish in menu:
if any(ingredient in menu):
return False
return True
menu = [
['soup','onion','potato','leek','celery'],
['pizza','bread','tomato','cheese','cheese'],
['banana']
]
CodePudding user response:
for dish in menu:
if ingredient in dish:
return False
return True
CodePudding user response:
You could have another for function that loops through each element in each dish in the menu to check if the specified unwanted ingredient is in the menu.
def free_from(menu: list, unwanted_ingredient: str):
for dish in menu:
for ingredient in dish:
if ingredient == unwanted_ingredient:
return False
return True
menu = [
['soup','onion','potato','leek','celery'],
['pizza','bread','tomato','cheese','cheese'],
['banana']
]
print(free_from(menu, 'onion')) # yes onion in menu
print(free_from(menu, 'garlic')) # no garlic in menu
CodePudding user response:
as others have said: if ingredient in dish:
not menu
I also added some tests:
def free_from(menu: list, ingredient: str):
"""Return whether ingredient is in dish.
Preconditions: menu = dish1, dish2, dish3
Postconditions: if menu has ingredient = false else true
"""
for dish in menu:
if ingredient in dish:
return False
return True
menu = [
['soup', 'onion', 'potato', 'leek', 'celery'],
['pizza', 'bread', 'tomato', 'cheese', 'cheese'],
['banana']
]
testIngredients = ["soup", "banana", "cake", "turkey", "cheese"]
expected = [False, False, True, True, False]
output = []
for ingredient in testIngredients:
output.append(free_from(menu, ingredient))
print(expected)
print(output)
print(output == expected)
output:
[False, False, True, True, False]
[False, False, True, True, False]
True