【问题标题】:How to speed up of simple algorithm that takes inputs from user如何加速从用户那里获取输入的简单算法
【发布时间】:2020-10-03 14:12:27
【问题描述】:

我想知道如何加快以下代码的速度。它接受用户的输入并打印重复次数最多的项目。第一个输入是用户想要输入的值的数量。

N = int(input())
B=[]
for i in range(N):
    b = (int(input()))
    B.append( (b) )
print(max(set(B), key=B.count)) 

【问题讨论】:

  • 我无法想象一个人输入足够多的数字会使这变慢。运行需要多长时间?
  • 机器人可以输入数字,可能是千。我需要不到 5 秒。

标签: python performance for-loop printing


【解决方案1】:

您可以使用collections.Counter

from collections import Counter

Counter(B).most_common(n=1)[0][0]

时间比较:

from random import randint

B = [randint(0, 25) for _ in range(10000)]

%%timeit
max(set(B), key=B.count)
# 3.89 ms ± 63.4 µs per loop

%%timeit
Counter(B).most_common(n=1)[0][0]
# 434 µs ± 53.8 µs per loop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多