user6939454
user6939454

Reputation: 1

Selecting multiple elements from array python

this is a pretty basic question but here goes:

I would like to create an array and then would like to compare a user input to those elements within the array.

If one element is matched then function 1 would run. If two elements were matched in the array the an alternative function would run and so on and so forth.

Currently i can only use an IF statement with no links to the array as follows:

def stroganoff():
    print ("You have chosen beef stroganoff")
    return

def beef_and_ale_pie():
    print ("You have chosen a beef and ale pie")
    return

def beef_burger():
    print ("You have chosen a beef burger")
    return

ingredients = ['beef','mushrooms','ale','onions','steak','burger']

beef = input("Please enter your preferred ingredients ")

if "beef" in beef and "mushrooms" in beef:
    stroganoff()
elif "beef" in beef and "ale" in beef:
    beef_and_ale_pie()
elif "beef" in beef and "burger" in beef:
    beef_burger()

As said, this is basic stuff for some of you but thank you for looking!

Upvotes: 0

Views: 288

Answers (3)

Harsh Mehta
Harsh Mehta

Reputation: 259

Since you only can work with IF statements

beef=input().split()
#this splits all the characters when they're space separated
#and makes a list of them

you can use your "beef" in beef and "mushrooms" in beef and it should run as you expected it to

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

You may do something like:

# Dictionary to map function to execute with count of matching words
check_func = {
    0: func_1,
    1: func_2,
    2: func_3,    
} 

ingredients = ['beef','mushrooms','ale','onions','steak','burger']
user_input = input()

# Convert user input string to list of words
user_input_list = user_input.split()

# Check for the count of matching keywords
count = 0
for item in user_input_list:
    if item in ingredients:
        count += 1

# call the function from above dict based on the count
check_func[count]()

Upvotes: 0

wonce
wonce

Reputation: 1921

So I understand your question such that you want to know, how many of your ingredients are entered by the user:

ingredients = {'beef','mushrooms','ale','onions','steak','burger'}

# assume for now the inputs are whitespace-separated:
choices = input("Please enter your preferred ingredients ").split()

num_matches = len(ingredients.intersection(choices))
print('You chose', num_matches, 'of our special ingredients.')

Upvotes: 0

Related Questions