Python 3.x 为什么我的python代码会出现运行时错误?
这是我在这个平台上的第一个问题,我是Python编码新手。这个问题是HackkerRank的一个难题。你能为我的编码提出任何解决方案吗?它给出了运行时错误:Python 3.x 为什么我的python代码会出现运行时错误?,python-3.x,Python 3.x,这是我在这个平台上的第一个问题,我是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]]
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
提前感谢。缩短代码-您使用的中间列表太多-它们都需要时间来构建、填充和使用:
# 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
你得到了什么错误?我有运行时错误。如果需要很长时间,Hackerrank将为有效代码生成错误-这就是你所说的“运行时”吗?如果是这样:优化您的解决方案以加快速度。问题的黑客链接url是什么?我猜这是由于优化,编译中输入了1000个输入。那么我应该怎么做,是否应该将for循环更改为其他内容?