I have to create a program that lets a user input what courses they have taken(one at a time), and compare it to a dictionary of "courses" with the pre-requisites and print what courses that student is eligible to take. I am not sure on how to compare the user input to the dictionary to print what courses they can take. Here is what I have so far
print "Enter a course(0 to quit): "
courses = raw_input()
d = {150:[150],
161:[161],
162:[161],
231:[162],
241:[161],
251:[251],
260:[150],
300:[241],
303:[162],
304:[162],
307:[162],
353:[231],
385:[353],
355:[231],
461:[303,304,307,231],
475:[303,304,307],
480:[470]
}
while courses =! '':
if courses in d.keys():
print("You have taken: ", courses)
if courses == 0:
break
You are only getting input once. You need to get input in a loop:
d = {150:[150],161:[161],162:[161],231:[162],241:[161],251:[251],260:[150],300:[241],303:[162],304:[162],307:[162],353:[231],385:[353],355:[231],461:[303,304,307,231],475:[303,304,307],480:[470]}
prereqs = set()
while True:
course = int(raw_input("Enter a course you have taken (0 to quit): "))
if course == 0:
break
try:
prereqs.update(d[course])
except KeyError:
print '\t\t\t\t\tHmm...I don\'t know that course'
In the while loop, we are getting input every iteration. If it is 0, we break out of the loop. If not, we try to lookup the course in the dict. If this fails, we print the "error" message. You should be able to take it from here(prereqs stores the courses that you have took in a set).
Related
I am completing the 30 day hackerrank challenge. This is the question: Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. I've managed to pass all the test cases except 1, I got a runtime error when the numberOfEntries was 1000. How do I fix this?
numberOfEntries = int(input())
phoneBook = dict()
for i in range(0,numberOfEntries):
entry = input()
temp = entry.split(" ")
phoneBook[temp[0]] = int(temp[1])
for index, item in enumerate(phoneBook):
query = input()
if index == numberOfEntries:
break
if query in phoneBook.keys():
print(f"{query}={phoneBook[query]}")
else:
print("Not found")
Thank you for everyone's input. Turns out the only thing I needed to do was:
numberOfEntries = int(input())
phoneBook = dict()
for i in range(0,numberOfEntries):
entry = input()
temp = entry.split(" ")
phoneBook[temp[0]] = int(temp[1])
for index, item in enumerate(phoneBook):
try:
query = input()
if index == numberOfEntries:
break
if query in phoneBook.keys():
print(f"{query}={phoneBook[query]}")
else:
print("Not found")
except:
break
I'll definitely edit the code to make sure it accepts operators and 0's too, so thank you!
I am trying to make a short program which will take user input, append the input to a list and then randomly determine the order of the elements in the list.
this is what I thought out:
from random import choice
participants = []
prompt = "\nPlease enter players first name: "
prompt += "\nPlease enter 'q' when all players have been entered: "
while True:
user = input(prompt)
if user == 'q':
break
print(f"There are {slot} participants")
else:
participants.append(user)
slot = len(participants)
print("\n\n")
for participant in participants:
print(f"{participant}")
print(f"So far, there are {slot} participants")
while participants:
for participant in participants:
person_of_choice = choice(participants)
person_in_question = participants.remove(person_of_choice)
print(person_in_question)
However, I am getting the following output
Mark Stark Dark So far, there are 3 participants
Please enter players first name: Please enter 'q' when all players
have been entered: q None None None
How do I change the ordering from none into their names?
I've changed a few things in the code, and the changes are commented out with ##.
you can try it to see the output.
from random import choice
participants = []
prompt = "\nPlease enter players first name: "
prompt += "\nPlease enter 'q' when all players have been entered: "
# init slot to zero
slot = 0
while True:
user = input(prompt)
if user == 'q':
print(f"There are {slot} participants")
## if you want to use `print` function before `break`,
## you must put the `break` statement under the `print` function
break
else:
participants.append(user)
slot = len(participants)
print("\n\n")
for participant in participants:
print(f"{participant}")
print(f"So far, there are {slot} participants")
while participants:
for participant in participants:
person_of_choice = choice(participants)
print(person_of_choice)
# person_in_question = participants.remove(person_of_choice)
## person_in_question is None, because `remove` always return None
## you can this from here https://docs.python.org/3/tutorial/datastructures.html
participants.remove(person_of_choice)
So, I'm taking a few courses through Udemy. The final project on the Python 3.x course has you making a simple UI which I did fine.
The premise is a grade tracker for students. You could add grades, remove a student, average the student grades, and exit from the program.
I wanted to do something not in the lesson, and that was be able to add new students. I added another option. I've tried entering what I thought would work, but I keep getting errors. I could finally enter a new student, but then when I tried to add a grade for that student, it would say the student didn't exist, even though they showed up in the dictionary.
So, any clue how I can accomplish this?
Any and all assistance is greatly appreciated. Code to follow:
#Making a Python Program
from statistics import mean as m
admins = {'Python':'Pass123#', 'user2':'pass2'}#this will be here authorized users and passwords would be
studentDict= {'Jeff':[78,88,93],
'Alex':[92,76,88],
'Sam':[89, 92, 93]}
def enterGrades():
nameToEnter= input('Student Name: ')
gradeToEnter= input ('Grade: ')
if nameToEnter in studentDict:
print('Adding Grade...')
studentDict [nameToEnter].append(float(gradeToEnter))
else:
print ('Student does not exist.')
print (studentDict)
def removeStudent():
nameToRemove = input ('Which student do you want to remove?: ')
if nameToRemove in studentDict:
print('Removing student...')
del studentDict[nameToRemove]
print (studentDict)
def addStudent():
nameToAdd = input ('Enter the name of the new student: ')
if nameToAdd in studentDict:
print ('Student already exists.')
else:
print ('Adding new student...')
studentDict[nameToAdd]
print (studentDict)
#Crashes upon entering student name.
def studentAVGs():
for eachStudent in studentDict:
gradeList= studentDict[eachStudent]
avgGrade = m(gradeList)
print(eachStudent, 'has an average grade of', avgGrade)
def main():
print("""
Welcome to Grade Central
[1] - Enter Grades
[2] - Remove Student
[3] - Add Student
[4] - Student Average Grades
[5] - Exit
""")
action= input ('What would you like to do today? (Enter a number) ')
if action == '1':
enterGrades()
elif action == '2':
removeStudent()
elif action == '3':
addStudent()
elif action == '4':
studentAVGs()
elif action == '5':
exit()
else:
print ('No valid choice was given, try again')
login= input('Username: ')
passw= input('Password: ')
if login in admins:
if admins[login] == passw:
print('Welcome,',login)
while True:
main()
else:
print('Invalid Password, will detonate in 5 seconds')
else:
print ('Invalid username, calling the FBI to report this')
You cannot add a key without a value. Also, since you expect a "student" record to be a list, you might as well create it with an empty list:
def addStudent():
nameToAdd = input ('Enter the name of the new student: ')
if nameToAdd in studentDict:
print ('Student already exists.')
else:
print ('Adding new student...')
studentDict[nameToAdd] = []
print (studentDict)
Since you are making a dictionary of students as keys and pointing them to a list might I suggest you take advantage of python's amazing higher order data structures? Specifically the defaultdict? As for your problem if you apply a default dict you can easily handle this problem you are having. As below.
from collections import defaultdict
studentDict = defaultdict(list)
#rest of your code will now work because all keys you enter in your
#addStudent() function will have an automatic value of an empty list
My name is Jamie, I'm a Yr 12 student currently living in NZ. At school, in our computer science class we were tasked with creating a program for house points. A house is sort of like the Houses in Harry Potter, each student is assigned to one. These houses then compete in events and earn points, at the end of the year the house with the most points wins the trophy.
Now we have only been taught about 2-D arrays and parallel lists, as these need to be incorporated plus it must be modular.
The program must be fully user inputed as requirements for excellence (equivalent of A) must be user inputed.
The program must also have these inputs and outputs:
Inputs: House Names, House Events, and Points earned in events for the house
Cancel house name and house event entry when XXX is entered.
Outputs: Winner of each event, house with best average, house with most wins, and overall winner.
I am currently trying to figure out how to do the points to go with house and events.
Appreciate all help,
Jamie :)
EDIT: Posted Code
def number_house():
global numhouse
print("Welcome!")
print()
Flag = True#loop
while Flag:
try:
numhouse = int(input("Please enter the number of events there is: "))
print()
if numhouse < 1 or numhouse > 100:
print("WOW, thats a lot of events, please be reasonable. Thanks.")
else:
Flag = False
except ValueError:
print("Enter only a number, Thanks.")
def event_names():
global event
print("Enter XXX when finished entering event names")
Flag = True
for e in range(numhouse):
e = input("Event name: ")
if e == 'XXX' or e == 'xxx':
Flag = False
else:
event.append(e)
print()
def getData():
global data
global inputlist
global event
lower_bound = 0
upper_bound = 100
k=0
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
while n != 'XXX' :
if n == 'XXX' or n == 'xxx':
exit
data = [n]
print()
print ("Please enter the event points in ascending order. ",event,"Thanks")
for k in range(len(event)):
s = getScore(n,lower_bound,upper_bound)
data=data+[s]
inputlist = inputlist + [data]
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
def getScore(name,min,max):
global event
sc= -1
while sc < min or sc > max :
try :
sc = int(input("Please enter score for "+ name + " :"))
except ValueError :
print("Invalid Input please enter an interger. Thanks")
return sc
score =[]
getscore = []
data = []
inputlist = []
event = []
number_house()
event_names()
getData()
print()
print(inputlist)
LOWER_BOUND = 0
UPPER_BOUND = 100 # both in caps because this is a constant
def get_score(house_name, event_name):
# an extra argument so you can tell which event is being scored.
# removed the min, max cause we are using the constants!
score = -1
while score < LOWER_BOUND or score > UPPER_BOUND:
try:
score = int(input("Please enter score for %s in the event %s:" % (house_name, event_name)))
if score < LOWER_BOUND :
print ("Score is too low, minimum score is %i.\nPlease try again." % min_score)
if score > UPPER_BOUND:
print ("Score is too high, maximum score is %i\nPlease try again." % max_score)
except ValueError:
print("Invalid Input please enter an integer. Thanks")
return score # note the use of return to avoid using global
def get_number_of_events():
print("Please enter the number of events there is.")
while True:
try:
n_events = int(input(">>"))
except ValueError:
print("Enter only a number, Thanks.")
if n_events > 100:
print("WOW, that's a lot of events, please be reasonable. Thanks.")
elif n_events < 1:
# this is a different condition that would get a wrong error in your program,
# note the use of 'elif', in Python this an 'else if'.
print ("That's too few events! Try Again.")
else:
# no need to use Flag, just use break when you want to leave a loop.
break
return n_events
def get_events_names(n_events):
print ("Please enter the events names")
events = []
for n in range(1, n_events + 1):
# starting at 1 to give a better display
event_name = input("Event %i name: " % n)
events.append(event_name)
return events
def get_data(events):
data = []
while True:
house_name = input("Please enter house names <<<Enter XXX when finished>>> :")
if house_name.upper() == "XXX":
# using .upper() to avoid checking twice for either 'xxx' or 'XXX'.
# I would ask the user for how many houses are there instead, but your choice ;)
break
print ("Please enter the events points in ascending order.")
# not actually need to be in ascending order, you can sort them later if you want.
scores = []
for event_name in events:
# don't use range(len(something)), loops in Python are easy!
score = get_score(house_name, event_name)
scores.append([event_name, score])
data.append([house_name, scores])
# use .append() instead of data = data + [...]
return data
def main():
print("Welcome!\n")
n_events = get_number_of_events()
events_names = get_events_names(n_events)
print()
data = get_data(events_names)
print()
for house_name, event_data in data:
print ("House " + house_name)
for event_name, score in event_data:
# note the use of tuple unpacking
print ("\tEvent: %s Score: %i" % (event_name, score))
if __name__ == '__main__':
main()
This time maintaining the same structure as your program.
Check comments for some tips and tricks.
Also, try to keep your variable names with meaning and check the PEP 8 guidelines for naming conventions (variables and functions should be snake_case,
Output:
Welcome!
Please enter the number of events there is.
>>2
Please enter the events names
Event 1 name: Quidditch Match
Event 2 name: Duels
Please enter house names <<<Enter XXX when finished>>> :Gryffindor
Please enter the events points in ascending order.
Please enter score for Gryffindor in the event Quidditch Match:100
Please enter score for Gryffindor in the event Duels:30
Please enter house names <<<Enter XXX when finished>>> :Slytherin
Please enter the events points in ascending order.
Please enter score for Slytherin in the event Quidditch Match:40
Please enter score for Slytherin in the event Duels:50
Please enter house names <<<Enter XXX when finished>>> :XXX
House Gryffindor
Event: Quidditch Match Score: 100
Event: Duels Score: 30
House Slytherin
Event: Quidditch Match Score: 40
Event: Duels Score: 50
I'll try to give you a different approach, see if that helps you.
def main():
events = []
houses = []
scores = {} # key = House name, value = scores
print "Welcome!\n"
# create the houses
print "Please enter how many houses there is:"
n_houses = int(raw_input(">>"))
print "Please enter houses names:"
for n in range(n_houses):
print "House", n+1
house_name = raw_input(">>")
houses.append(house_name)
# create the events
print "Please enter the number of events there is"
n_events = int(raw_input(">>"))
print "Please enter the event names"
for n in range(n_events):
print "Event", n+1
event_name = raw_input(">>")
events.append(event_name)
# get the scores for each house for each event
for event in events:
for house in houses:
print "Please enter the score for House %s in the event %s"%(house, event)
score = int(raw_input(">>"))
# initialize the score with a empty list
if house not in scores:
scores[house] = []
# add the score list
scores[house].append(score)
print "\nThe result is:"
# process the result
for house, score in sorted(scores.items(),
key=lambda x: sum(x[1]),
reverse=True):
print "House %s. Total Score: %i"%(house, sum(score))
if __name__ == "__main__":
main()
First thing you should notice is that I'm not using global, using global is usually frowned upon, it can lead to undesired interactions on data.
Also, instead of asking for inputs like "XXX" to break the loop, I asked the user for the number of inputs he wants to deal before, so I can loop over this number and process each separately.
I do the same thing with the house, I ask for how many houses are there, and then their names.
Next I do a nested for loop with the event names and house names. The order matters, we deal with each event first. You can change it to deal with each house first.
And finally I process the scores. the line for house, score in sorted(scores.items(), key=lambda x: sum(x[1]), reverse=True): is a bit clogged and advanced but it means this: I want to loop over a sorted list of items, giving me two items at a time, the items are named house and score, they will be sorted by the function sum(x[1]), and I want this in the reversed order (or else the last would show in first).
key=lambda x: sum(x[1]) is a bit of a hack, it could be done better. lambda means a function, it takes x as input, x in this case is a tuple of house, score, so I want the score, so I access it using x[1], and since I want the sum I use sum(x[1]).
Usage:
Welcome!
Please enter how many houses there is:
>>2
Please enter houses names:
House 1
>>Gryffindor
House 2
>>Slytherin
Please enter the number of events there is
>>2
Please enter the event names
Event 1
>>Quidditch Match
Event 2
>>Duels
Please enter the score for House Gryffindor in the event Quidditch Match
>>100
Please enter the score for House Slytherin in the event Quidditch Match
>>90
Please enter the score for House Gryffindor in the event Duels
>>250
Please enter the score for House Slytherin in the event Duels
>>240
The result is:
House Gryffindor. Total Score: 350
House Slytherin. Total Score: 330
Notice that this was made on Python 2.7, to port to Python 3 just change raw_input to input and print to print()
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...