简体   繁体   中英

How to fix runtime error in my dictionary code in python?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM