【问题标题】:Python Input PerformancePython 输入性能
【发布时间】:2015-12-30 16:56:51
【问题描述】:

背景

我一直在尝试通过 Kattis 上提供的优秀挑战来复习我的 Python 知识。我现在对需要高效率的this problem 感到困惑。我的解决方案得到了正确的答案,但太慢了。虽然其他语言可能会更快,但我从统计数据中知道它可以使用 Python 3 解决。

问题

给程序一个整数长度,然后是一个包含整数值的长度列表。我将这些添加到一个列表中,但是当我得到很长的列表时,程序在完成读取输入之前超过了 3 秒的时间限制。

任何关于如何加快速度的建议将不胜感激!

到目前为止的代码(已更新理解)...

Gist copy

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


【解决方案1】:

也许您可以尝试使用列表推导来接收输入:

nums = [input() for i in range(length)]

列表推导通常比使用 for 循环附加到列表更快。在此处查看有关不同速度和不同循环方法的一些信息,https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops

【讨论】:

  • 那个链接真的很有帮助,谢谢。我现在已经开始使用列表理解了;虽然我还没有突破读取 200,000 行输入的 3 秒限制。
  • 也许生成器有助于加快速度。不过,从事物的声音来看,也许整个程序可以在这里和那里进行一些优化。我自己也去看看。
【解决方案2】:

您应该使用列表推导。附加要求每次都查找该方法,而列表推导则更加优化:

inputList = [input() for _ in range(length)]

【讨论】:

  • 这很有意义,干杯。我已经开始在输入中使用列表推导,并且也会考虑改进其他循环。即使进行了此更改,仍然会遇到输入时间限制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多