如何加快我的代码?蟒蛇

时间:2017-11-14 08:52:57

标签: python performance

我需要我的代码更快地工作,这个我目前有时甚至需要5秒才能打印答案。

import math 

n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)

answer_list = []
q = 0
w = 1
e = 2

for l in range(range_is):
    o = myList[q]+myList[w]+myList[e]
    answer_list.append(o)
    if e == n-1 and w == n-2  and q != n-3:
        q = q+1
        w = q+1
        e = w+1

    elif e == n-1 and w != n-2: 
        w = w+1
        e = w+1

    elif e != n:
        e = e+1  

answer_list.sort()
print(answer_list[k-1])

如何让它跑得更快?这段代码中的问题是什么,以后我可以避免这个问题?

2 个答案:

答案 0 :(得分:2)

您的问题应该写什么

总结:

  • 您有一个n整数列表。
  • 您想要计算p整数的每个组合。
  • 您想要计算每个组合的总和。
  • 您想要对这些金额进行排序。
  • 你想要k - 总和。

代码itertools.combinations

通过此描述,代码变得简单:

from itertools import combinations

n = 5
p = 3
k = 4

integers = range(1, n + 1)
triples = combinations(integers, p)
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
triple_sums = [sum(t) for t in triples]
# [6, 7, 8, 8, 9, 10, 9, 10, 11, 12]
triple_sums.sort()
# [6, 7, 8, 8, 9, 9, 10, 10, 11, 12]
print(triple_sums[k - 1])
# 8

使用itertools.combinations可能会加快您的代码速度,尤其是因为您不需要为大型math.factorial(n)计算n

最重要的是,这段代码更简洁,更好地展示了你的意图。

性能

令人遗憾的是,即使triple_sums已排序,integers也未排序。需要计算每个组合,并且必须对整个列表进行排序。可能有另一种方法来生成triple_sums将直接排序的组合,但我想不出任何组合。

如果您的列表有7000个整数,则会有57142169000个三元组。使用itertools对性能无济于事。您需要提供有关列表和k的更多信息。

答案 1 :(得分:-4)

一些建议:

1,使用python 2代替python 3。

2,计算大数时, 使用“xrange”代替“range”; 使用“ifilter”而不是“filter”。

3,如果使用迭代算法,请尝试使用“yield”。

相关问题