这是我在这个平台上遇到的第一个问题,我是Python编码的新手。这个问题是HackkerRank中的一个挑战。您能为我的编码提出任何解决方案吗?它给出了运行时错误:
n=int(input())
phoneBook={}
pb=[]
list1=[]
for i in range(n):
k=str(input())
pb.append(k)
list1.append(k.split(" "))
for j in range (2):
phoneBook[list1[i][0]]=list1[i][1]
b='at'
try:
while b != "":
b=str(input())
if any(b in s for s in phoneBook):
print(b,"=",phoneBook[b],sep='')
else:
print("Not found")
except EOFError:
pass
先谢谢了。
答案 0 :(得分:0)
缩短的代码-您使用了太多的中间列表-它们都需要时间来构造,填充和使用:
# create the phone book
d = {}
for n in range(int(input())):
# repeat input() and strip/split/strip it into the dict
# use list decomposition instead of a list over a range of indext list values
name,number = [x.strip() for x in input().strip().split()]
d[name]=number
# read and produce numbers until done
while True:
try:
q = input()
# no need for if any(b in s for s in phoneBook):
# dictionary is fast for testing if key in it
# I would prefer dict.get(key,default) but for the wanted
# output this is easier / better
if q in d:
# use string formating
print("{}={}".format(q, d[q]))
else:
print("Not found")
except EOFError:
break