【发布时间】:2015-12-30 16:56:51
【问题描述】:
背景
我一直在尝试通过 Kattis 上提供的优秀挑战来复习我的 Python 知识。我现在对需要高效率的this problem 感到困惑。我的解决方案得到了正确的答案,但太慢了。虽然其他语言可能会更快,但我从统计数据中知道它可以使用 Python 3 解决。
问题
给程序一个整数长度,然后是一个包含整数值的长度列表。我将这些添加到一个列表中,但是当我得到很长的列表时,程序在完成读取输入之前超过了 3 秒的时间限制。
任何关于如何加快速度的建议将不胜感激!
到目前为止的代码(已更新理解)...
import collections
length = int(input())
inputList = []
maxVal = 0
# Set offers O(1) when checking if an element is present.
history = set()
results = []
impossible = False
inputList = [input() for _ in range(length)]
# Map int conversion and convert to deque for O(1) removal from left later on.
# Is this worth it?
inputDeque = collections.deque(map(int, inputList))
# Find highest value. Was doing this during input,
# moved here to potentially speed up input loop.
maxVal = max(inputDeque)
# There must be a smarter way here,
# but we're not getting this far on large inputs yet.
# For every element of input,
# find the lowest value that is not in the remaining input or history.
for _ in range(length):
for i in range(1, 200000, 1):
# If the lowest value we can get is higher than the largest input, this can't be solved.
if i >= maxVal:
impossible = True
break
if i not in history and i not in inputDeque:
results.append(i)
history.add(i)
inputDeque.popleft()
break
if impossible:
break
if impossible:
print('Error')
else:
[print(i) for i in results]
非常感谢!
【问题讨论】:
-
为什么不稍后打印/格式化结果并使用列表而不是添加到字符串?字符串是不可变的,python 需要为每个元素创建一个新对象(并连接值)
-
@Pynchia 好点!我会这样做的,谢谢。
标签: python performance parsing input io