Selecting multiple elements from array python - 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!

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

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.')

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]()

Related

How to modify python program to ask user what section it wants to run and only runs that section? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 days ago.
I am trying to add a way to ask the user what problem(1-5)they would like to run of the program. This should be repeated until the user enters an invalid input.
I think I just do not understand the logic behind it. I have looked into a lot and I still don't understand what I can do to separate the problems.
Here is the code that I have to work with:
#Problem 1
#create variable called fruits, store listed fruits, print num of items in list
#insert Orange, append Plum, remove Melon, reprint
fruits = ['Apple', 'Banana', 'Cherry', 'Kiwi', 'Melon', 'Mango']
print("Initial fruits list:", '\n', fruits)
print("-"*56)
q1= len(fruits)
print ("q1: the len of fruits is", q1)
fruits.insert(3, 'Orange')
print("q2: inserted Orange between Cherry and Kiwi:", '\n', fruits)
fruits.append('Plum')
print("q3: appended plum to the end:", '\n', fruits)
##fruits.insert(7, 'Plum') #testing if insert works
##print(fruits)
print("Can use insert function to add an item to the end of the list")
fruits.remove('Melon')
print("q4: removed melon from the list:", '\n', fruits)
#Problem 2
#prompts user for a name, stores in variable called n
#display how many times lowercase 'a' appears within name
n= input("Please enter a name:")
char = 'a'
count = 0
for i in range(len(n)):
if(n[i]== char):
count = count+1
print("character", char, "appears", count, "time(s) within the name", n)
#Problem 3
#modify previous code to accept both uppercase and lowercase
#use upper() and lower() functions
n= input("Please enter a name:")
def eCount(n):
return n.lower().count('a')
print("character a appears", eCount(n), "time(s) within the name", n)
#Problem 4
#Prompts user 5 times for integer, stores in list, display list
#print min, max, and avg
num1=int(input("Please enter a number:"))
num2=int(input("Please enter a number:"))
num3=int(input("Please enter a number:"))
num4=int(input("Please enter a number:"))
num5=int(input("Please enter a number:"))
list= [num1,num2,num3,num4,num5]
print("Number list is:", list)
minlist= min(list)
maxlist= max(list)
avglist= num1+num2+num3+num4+num5 /5
print("Min value is", minlist, ",","the max value is", maxlist,",", "and the average is", avglist)
#Problem 5
#create variables numList and numTuple, use slice operator, index() function
#membership operator, concatenate 2 sequences
numList= [-4,0,2,10]
print("Original List:", numList)
numTuple= (2,3,1)
print("Original Tuple:", numTuple)
print("-"*40)
print("Using slice operator on numList:",numList[1:3])
print("Using slice operator on numTuple:",numTuple[1:])
print("-"*40)
indexL= numList.index(2)
print("The index number of 2 in numList is",indexL)
indexT= numTuple.index(2)
print("The index number of 2 in numTuple is", indexT)
print("-"*40)
if -4 in numList:
print("-4 is a member of numList:",True)
else:
print("-4 is a member of numList:",False)
if -4 in numTuple:
print("-4 is a member of numTuple:",True)
else:
print("-4 is a member of numTuple:",False)
print("-"*40)
convTuple= list(numTuple)
concList= numList+convTuple
print("Concatenated as a list:", concList)
convList= tuple(numList)
concTuple= convList+numTuple
print("Concatenated as a list:", concTuple)
Are you talking about something like this?
def f():
while True:
take = input('Which problem you want to select?')
try:
id = int(take)
if id > 0 and id <=5:
return id
except Exception as e:
pass
if __name__ == "__main__":
id = f()
print(f'user selected {id}')

Return a result in descending order

Teachers of Horizon Academy Public School collect the names of those students who are going to participate in the Mathematics exhibition, that is to be held in a week's time. They have collected all the names and now, they want to store all the names into a system, in the descending order of the length of the names. This means, the longest name should get stored first, followed by the name that is shorter than the previous, and so on. Can you help the teachers to perform this task easily by creating a program in Python?
Note: The number of names specified must be positive, else the program should display the message "Invalid Input" terminate the program.
Input format:
Input consists of an integer that corresponds to the number of names followed by the names.
Output Format:
Print the name list sorted by the names' length, if name length are equal sort based on alphabetical order in descending order as shown in the sample input and output.
Sample Input 1:
Enter the number of names :
5
Enter the names:
William
James
Ella
Lily
Jackson
Sample Output 1:
The sorted name list is:
William
Jackson
James
Lily
Ella
Sample Input 2:
Enter the number of names:
Sample Output 2:
Invalid Input
Sample Input 3:
Enter the number of names :
3
Enter the names:
Lily
Jack
Lucy
Sample Output 3:
The sorted name list is:
Lucy
Lily
Jack
Above is the question and below is my code.
n=int(input("Enter the number of names:\n"))
l=[]
if n>0:
print("Enter the names:")
for i in range(n):
l.append(input())
print("The sorted name list is:")
l.sort(key=len,reverse=True)
for i in l:
print(i)
else:
print("Invalid Input")
I can't seem to figure out why I can't sort it alphabetically. Any suggestion? For example if my input is "Lily, Jake, Lucy", I want it to display the result "Lucy, Lily, Jake"
The issue in the code is that you are specifying a key to sort. It is currently sorting by length in decending order. I tried this and it gets the result you are looking for:
people = ['Lily', 'Lucy', 'Jack']
people.sort(reverse=True)
print(people)
Read more about sort() here
Hi I think you're misunderstanding the behavior of the <list>.sort() method, here you don't need to use the key parameter:
number_of_names = int(input('Number of names: '))
names = list()
if number_of_names > 0:
print('Enter the names:')
for _ in range(number_of_names):
names.append(input())
names.sort(reverse=True)
for name in names:
print(name)
Key isn't useful there, it can be if you want to modify each key, for example, if I want to sort my items after applying a specific transformation:
l = ["tato", "taty", "tyta", "tate"]
# if I want to sort this list based on the last character of each items
l.sort(key=lambda x: x[-1])
# l = ['tyta', 'tate', 'tato', 'taty']
Actually this parameter, will be very useful when you have a list of dicts and you want to sort it based on a parameter:
users = [{"name": "Jack", "age": 22}, {"name": "John", "age": 16}]
users.sort(key=lambda user: user['age']) # sort the users by age
use reverse = True while using sort method
l = list(["Lilly", "Lucky", "Jack"])
l.sort(key=lambda x: x, reverse=True)
print(l)
Updated ans:
key = len doesn't make sense
n=int(input("Enter the number of names:\n"))
l=[]
if n>0:
print("Enter the names:")
for i in range(n):
l.append(input())
print("The sorted name list is:")
l.sort(reverse=True)
for i in l:
print(i)
else:
print("Invalid Input")
Output:
$ python3 test.py
Enter the number of names:
3
Enter the names:
Lilly
Lucky
Jack
The sorted name list is:
Lucky
Lilly
Jack

Check element in list of array Python [duplicate]

This question already has answers here:
Check if element exists in tuple of tuples
(2 answers)
Closed 1 year ago.
I want to check if there is an element in a list of array
for example, I have:
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
So if I want to check if "horse A" is in the list. I tried:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
But if I input the horse name is : "horse B".
Input will also check every array in the list and print out the statement not found in array 1.
input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment:
So how can I get rid of that ? Thank you.
You just need to move the else to be part of the for loop:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check, treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
You need to print the "horse not found" message only after traversing all the list, not very time you find an element. And you should exit the loop after finding the correct horse, no point in iterating beyond that point. You should use for's else construct for this:
horsename_check = input("Enter horse name: ")
for i in horselist:
if i[1] == horsename_check:
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
if neededHorse in horse:
found = horse[0]
if found != 0:
print("Horse found in ",found)
else:
print("Horse not found!")
This should work, you can keep a condition outside the loop and check it post the loop

Deleting items from a list with a less than operator

I am working on a program for a class which has us build a craigslist type of program.
myStr=[]
b = "bike"
ans = True
while ans:
print "1. Add an item"
print "2. Find an item"
print "3. Print the message board"
print "4. Quit"
choice = input("Enter your selection: ")
if choice == 1:
itemType = raw_input("Enter the item type-b,m,d,t,c: ")
itemCost = input("Enter the item cost: ")
myStr.append([itemType,itemCost])
if choice == 2:
itemType = raw_input("Enter the item type-b,m,d,t,c: ")
maximum = input("Enter the maximum item cost: ")
print maximum
if choice == 3:
print myStr
if choice == 4:
break
Fairly easy to read what's going on here but I am missing a crucial part which is deleting entries from myStr. I tried using a for loop but it did not work. What I need it to do is delete the first entry that meets this criteria.
if maximum > itemCost then delete the first item in the list.
I can't wrap my brain around it so any help would be great.
Also, any other advice to improve my code is welcome!
You could try something extracting the list of items whose cost is greater than maximum and then removing those items from your list. List comprehension is great at it.
max_cost = 3
myStr = [['Item1', 2], ['Item2', 3], ['Item3', 4]]
to_remove = [item for item in myStr if item[1] > max_cost]
for item in to_remove:
myStr.remove(item)
You could try with something like that.

python variable NameError

I am having trouble with assigning values to vars and then accessing the values. For example:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = 100Mb # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."
Traceback returns:
Traceback (most recent call last):
File "./ranSongList.py", line 87, in <module>
print "\nYou want to create a random song list that is " + tSize + "."
NameError: name 'tSize' is not defined
I have read up on python variables and they do not need to be declared so I am thinking they can be created and used on the fly, no? If so I am not quite sure what the traceback is trying to tell me.
By the way, it appears as though python does not offer 'case' capabilities, so if anyone has any suggestions how to better offer users lists from which to choose options and assign var values I would appreciate reading them. Eventually when time allows I will learn Tkinter and port to GUI.
Your if statements are checking for int values. raw_input returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
This should do it:
#!/usr/local/cpython-2.7/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = int(raw_input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is {}.".format(tSize)
BTW, in case you're open to moving to Python 3.x, the differences are slight:
#!/usr/local/cpython-3.3/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print("\nHow much space should the random song list occupy?\n")
print("1. 100Mb")
print("2. 250Mb\n")
tSizeAns = int(input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print("\nYou want to create a random song list that is {}.".format(tSize))
HTH
In addition to the missing quotes around 100Mb in the last else, you also want to quote the constants in your if-statements if tSizeAns == "1":, because raw_input returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns is guaranteed to be in the range of tSize. Otherwise you would have to either catch the KeyError exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"}
try:
tSize = lookup[tSizeAns]
except KeyError:
tSize = "100Mb"
or
from collections import defaultdict
[...]
lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"})
tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
I would approach it like this:
sizes = [100, 250]
print "How much space should the random song list occupy?"
print '\n'.join("{0}. {1}Mb".format(n, s)
for n, s in enumerate(sizes, 1)) # present choices
choice = int(raw_input("Enter choice:")) # throws error if not int
size = sizes[0] # safe starting choice
if choice in range(2, len(sizes) + 1):
size = sizes[choice - 1] # note index offset from choice
print "You want to create a random song list that is {0}Mb.".format(size)
You could also loop until you get an acceptable answer and cover yourself in case of error:
choice = 0
while choice not in range(1, len(sizes) + 1): # loop
try: # guard against error
choice = int(raw_input(...))
except ValueError: # couldn't make an int
print "Please enter a number"
choice = 0
size = sizes[choice - 1] # now definitely valid
You forgot a few quotations:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == "1":
tSize = "100Mb"
elif tSizeAns == "2":
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."

Categories

Resources