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!
Related
im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.
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).
Trying to create program to answer this question:
[ ] The records list contains information about some company's employees
each of the elements in records is a list containing the name and ID of an employee.
Write a program that prompts the user for a name and return the ID of the employee if a record is found
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
This is my code, so far:
ui = input('Enter employee name: ')
for row in records:
if row[0] in ui:
print(row[1])
else:
print('Employee not found!')
ui = input('Enter employee name: ')
I cannot seem to find a way to check if 'ui' is in the records list.
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
user_name = 'colette' # User input
for i in range(0,len(records)):
# Here I make User name and Name in Recored in lower case so it can match perfectly
if user_name.lower() in records[i][0].lower():
print(records[i])
else:
print("employee not found")
Associate the else block with the for loop instead of the if statement
ui = input('Enter employee name: ')
for row in records:
if row[0] == ui:
print(row[1])
break
else:
print('Employee not found!')
But, if you convert the nested list to a dict, it would be much easier to get the 'id'
ui = input('Enter employee name: ')
d = dict(records)
print(d.get(ui, 'Employee not found!'))
You can use list comprehension to do it -
[i for i in records if ui in i]
This will give you a list of list of employee you are trying to find else empty list.
For ex-
ui = 'Colette'
O/P -
[['Colette', 22347]]
You could do something like -
ui = input('Enter employee name: ')
found = [i for i in records if ui in i]
if found:
for emp in found:
print(emp[1])
else:
print("Employee not found")
This should take care of it, Do keep in mind when comparing two strings, python doesn't automatically convert uppercase to lowercase so its important if you intend to compare a string that you convert both the string in either lower or uppercase
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
ui = str.lower(input('Enter employee name: '))
names_to_compare=[t[0].lower() for t in records]
if ui in names_to_compare:
print(records[names_to_compare.index(ui)][1])
else:
print("Employee not in records")
The purpose of this program is to create a list of names for people attending a party. I would like to be able to grant the user the ability to continue adding names until they chose YES as an option to exit the loop. However, I have am stomped when it comes to having them enter a name they would like to remove in case they added someone by accident or if they would like to edit the list and remove or replace someone.
I am currently a newbie to programming, hence the lack of classes to this code. Any help would be greatly appreciated. Thank you all in advance!
#Initialize empty list
partyList = []
#Initilize empty entry
inviteeName = ''
endEntry = ''
#Run loop until YES is entered as a value
while endEntry != "Yes":
inviteeName = input("Please enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
# Verifies if a name was not entered.
while inviteeName == "":
inviteeName = input("\nPlease enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
endEntry = input("\tPress ENTER to continue or type Yes to finish: ")
endEntry = endEntry.title()
#Append every new name to the list
partyList.append(inviteeName)
#Adds the word "and" to finish sentence if there are more than one invitees. NOTE: Make a class please!
numOfInvitees = len(partyList)
if numOfInvitees > 1:
partyList.insert(-1, 'and')
#Remove brackets and quotes.
partyList = ', '.join(partyList)
#Print message
print("\nThis will be your final message:\n" + str(partyList) + "\nYou are invited to my party!\n")
I was trying to use this to assist the user with removing names entered by accident.
submit = input('Submit?: '.title())
submit = submit.title()
if submit == 'Yes':
print('Invite has been sent!')
elif submit == 'No':
remNameConfirmation = input('Would you like to remove a name from the list?: ')
remNameConfirmation = remNameConfirmation.title()
if remNameConfirmation == 'Yes':
uninviteName = (input('Who would you like to remove?: '))
uninviteName = uninviteName.title()
Here is the line that is giving some trouble
partyList.remove(uninviteName)
print(partyList)
When your code reaches
partyList = ', '.join(partyList)
it will set the variable partyList to a string. Since it is no longer a list it does not have the .remove method.
I am having trouble getting past writing user input to my list what am I doing wrong here? This is an address book program that I am writing, the assignment is to create parallel lists that will store user input data in the appropriate list using a for or while loop. The program must also have a search function which you can see is at the bottom of the code. My issue that I am having is getting the program to store data within my lists. Unfortunately lists are something that give me lots of trouble I just cant seem to wrap my head around it no matter how much research I have done. The issue im running into is the append.data function when trying to write lastname and firstname to my list of names. what am I doing wrong?
#NICHOLAS SHAFFER
#5/11/2016
#MYADDRESSBOOK
def menu():
index = 0
size = 100
count = 0
answer = raw_input("Are You Creating An Entry [Press 1] \nOr Are You Searching An Entry [Press 2] ")
if answer == "1" :
print ("This is where we create")
append_data(index, size, count)
elif answer == "2" :
print ("this is where we search")
search_database()
name[size]
phone[size]
addresss[size]
# IF we are creating
def append_data(index, size, count):
# collect information
for index in range(0, 100):
optOut = 'no'
while optOut == 'no':
lastname[count] = raw_input("What is the persons last name? ")
firstname[count] = raw_input("What is the persons first name? ")
phone[count] = raw_input("What id the persons phone number? ")
address[count] = raw_input("What is the persons address? ")
count = count + 1
print 'Would you like to create another entry?'
optOut = raw_input('Would you like to create another entry? [ENTER YES OR NO]:')
if optOut == 'yes':
menu()
#create string to print to file
#print temp1
#print (firstname + " " + lastname + ", " + phone + ", " + email + ", " + address)
print listName[index]
print listPhone[index]
print listAddress[index]
print 'file has been added to your addressbook sucessfuly'
menu()
# SEARCHING FOR A RECORD
def search_database():
searchcriteria = raw_input("Enter your search Criteria, name? phone, or address etc ")
print searchcriteria
if searchcriteria == "name":
temp1 = open(listName[lastname, firstname],"r")
print temp1
if searchcriteria == "phone":
temp1 = open(listPhone[0], "r")
print temp1
if searchcriteria == "address":
temp1 = open(listAddress[0], "r")
print temp1
else:
print "sorry you must enter a valid responce, try again."
menu()
for line in temp1:
if searchcriteria in line:
print line
errorMessage()
# USER DID NOT PICK CREATE OR SEARCH
def errorMessage():
print ("Incorrect Answer")
exit()
menu()
Your error message says it all:
line 34, in append_data lastname[count]... NameError: global name 'lastname' is not defined
You'll get this same error if you type lastname[4] in any interpreter -- you've simply never defined a list called lastname, so you can't access items in it. In the short term, you can fix this with a line
lastname = list()
You're going to end up with more troubles though; lastname won't be accessible outside the function where you define it, neither will listName. I'd probably approach that by writing them into a data file/database, or maybe creating a quick class whose members will all have access to self.lastname.
My final append for lists thanks again Noumenon
def append_data(index, size, count):
lastnames = list()
if count < size -1:
lastname = raw_input("What is the persons last name? ")
lastnames.append(lastname)
print lastnames
firstnames = list()
if count < size - 1:
firstname = raw_input("What is the persons first name? ")
firstnames.append(firstname)
print firstnames
phones = list()
if count < size - 1:
phone = raw_input("What id the persons phone number? ")
phones.append(phone)
print phones
addresss = list()
if count < size - 1:
address = raw_input("What is the persons address? ")
addresss.append(address)
print addresss
listName = (lastnames, firstnames)
addressbook =(listName, phones, addresss)
index = index + 1
count = count + 1
print addressbook
optOut = raw_input('Would you like to create another entry? [Enter YES or NO]: ')
if optOut == 'YES':
menu()
print 'file has been added to your addressbook sucessfuly'
menu()