gpt4 book ai didi

python - 我的 codejam 练习的解决方案或输出方法有什么不正确的地方?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:55:28 28 4
gpt4 key购买 nike

我参加了 google code jam 竞赛的 kickstart 并陷入了名为 Gbus count 的问题 1A我的代码通过了问题中提供的示例测试用例,但是当我通过将它输出到文件来提交小输入时,它给我一个错误,不正确的响应。

问题链接 - https://code.google.com/codejam/contest/4374486/dashboard#s=p0

t=int(input())    #no. of test cases 
for test in range(t):
if test==0:
n=int(input())
else:
input() #to cover up the blank line after each test case
n=int(input())
l=list(map(int,input().split()))

buses={} # the route of each bus will be stored in this dictionary
i=1

for d in l: # this loop is used to store the route of each bus in the buses dictionary
if i not in buses:
buses[i]=[d]
elif len(buses[i])<2:
buses[i].append(d)
else:
i=i+1
buses[i]=[d]

p=int(input())
cities={}
#this dictionary will contain the cities which need to be monitored
for _ in range(p): #first each city is initialized to zero
cities[int(input())]=0

for city in cities: #Monitor all buses in each city if it falls in the route range than increment the city
for bus in buses:
if buses[bus][0]<=city<=buses[bus][1]:
cities[city]+=1
result=[]

for city in cities: #store all the cities in a list
result.append(cities[city])

print("Case #{}: {}".format(test+1, ' '.join(map(str,result))))

我的逻辑:

首先,我将所有测试用例放入变量 t 中,并为每个测试用例输入编号。列表l中所有公交车的公交车和输入路线。然后我创建了一个名为 buses 的字典,并将列表分成 n 个列表,每个列表对应字典中从 1 到 n 的每条总线 nume=beres。

然后我在另一个名为cities的字典中输入了所有需要监控的城市,并将每个需要监控的城市的值初始化为0。

最后,我算了数。通过检查每个城市的公交车是否在每辆公交车的路线范围内,如果是,我将相应城市的值增加 1,然后将字典的所有值存储在一个列表中,并为每次测试输出它案例。

输出方法:

我使用这一行在我的工作目录中使用 cmd 执行我的代码

python gbus_count.py < A-small-attempt3.in > output.out

我的代码对于提供的示例测试用例运行良好,因此我的逻辑可能没有缺陷。我认为我的输出方法可能有误。

最佳答案

我在您的代码中发现了两个问题。

  1. Python 标准字典未排序!因此,cities 字典不会按照您输入的顺序包含元素(键)。
    • Python 3.1 开始,您可以使用 OrderedDict为此
  2. 如果同一个城市重复两次(或更多次),最终结果中将只有一个条目,因为字典不能容纳重复的键。

如我所见,您的设计具有流程。此外,我认为您可以轻松地做到这一点,而不会使事情变得太复杂。


注意:从 Python 3.6 开始,标准字典默认保持插入顺序。


更新

根据要求,以下是我解决问题的尝试。

请注意,这可能不是最佳解决方案!当然,这不是最易读的解决方案。这只是我的解决方案。

for case in range(1, int(input())+1):
if case > 1:
input('\n') # consume and print newline
print("Case #{}:".format(case), end='')
bus_count = int(input())
busline = list(map(int, input().strip().split(" ")))
for _ in range(int(input())):
city = int(input())
matches = sum([1 for bid in range(bus_count) if busline[2*bid] <= city <= busline[2*bid+1]])
print(" {}".format(matches), end='')

关于python - 我的 codejam 练习的解决方案或输出方法有什么不正确的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48973195/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com