如何提高追加然后检查列表中后续元素的效率
我正在尝试解决: http://orac.amt。 edu.au/cgi-bin/train/problem.pl?problemid=980&set=aio17int
该算法超出了较大文件的时间限制。我对 python 相当陌生,无法在网上找到更有效的解决方案来检查元素是否在列表中,然后进行相应的附加。请帮助提高速度而不使用任何导入。谢谢。
输入文件:
8 5
2 7
1 8
8 4
7 5
8 6
re = 1
bl = 1
red = [1]
blue = [2]
input_file = open("tagin.txt","r")
n, m = map(int, input_file.readline().split())
for i in range(m):
a, b = map(int, input_file.readline().split())
if a in red:
red.append(b)
re+=1
elif a in blue:
blue.append(b)
bl+=1
output_file = open("tagout.txt", "w")
output_file.write(str(re) + " " + str(bl))
output_file.close()
输出文件:
4 3
另请告知堆栈溢出是否是提出此问题的错误平台,如果是,我应该使用什么?
i'm attempting to solve:
http://orac.amt.edu.au/cgi-bin/train/problem.pl?problemid=980&set=aio17int
The algorithm exceeds the time limit for larger files. I'm fairly new to python, and can't find a more efficient solution online for checking if an element is in a list and then appending accordingly. Please help improve the speed without using any imports. Thank you.
input file:
8 5
2 7
1 8
8 4
7 5
8 6
re = 1
bl = 1
red = [1]
blue = [2]
input_file = open("tagin.txt","r")
n, m = map(int, input_file.readline().split())
for i in range(m):
a, b = map(int, input_file.readline().split())
if a in red:
red.append(b)
re+=1
elif a in blue:
blue.append(b)
bl+=1
output_file = open("tagout.txt", "w")
output_file.write(str(re) + " " + str(bl))
output_file.close()
output file:
4 3
Also please advise if stack overflow is the wrong platform to ask this question, if so what should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以改进的一些地方:
使用
集合
而不是列表
来收集团队成员。这将提高in
运算符的效率。无需跟踪团队的规模,因为您可以使用
len
函数获取该信息仅收集一个团队的成员。我们可以从
m
得出另一个团队的规模,它代表有多少人被标记。如果我们添加 2,我们还会考虑已标记的前两个。从中减去一个团队的规模,就可以得到另一个团队的规模。代码:
Some things you can improve:
Use a
set
instead of alist
for collecting team members. That will increase the efficiency of thein
operator.There is no need to keep track of the size of the team, as you can get that with the
len
functionOnly collect the members of one team. We can derive the size of the other team from
m
, which represents how many people get tagged. If we add 2 to that, we also take into account the first two which are already tagged. Subtract from that the size of one team, and you get the size of the other.Code:
如果我正确理解问题,那么这应该实现目标:
输出:
If I understand the problem correctly then this should fulfil the objective:
Output: