【发布时间】:2022-01-16 03:57:10
【问题描述】:
我正在编写一个 python 函数,该函数将 3 到 200 之间的整数值作为输入,使用等于该数字的唯一非零数字计算总和的数量并打印输出。 例如;以 3 作为输入 1 将被打印,因为只有 1 + 2 将给出 3,以 6 作为输入 3 将被打印,因为 1+2+3、1+5 和 2+4 等于 6。 我的代码仅适用于小于 30 的数字,之后它开始变慢。如何优化我的代码以高效运行 3 到 200 之间的所有输入。
from itertools import combinations
def solution(n):
count = 0
max_terms = 0
num = 0
for i in range(1,n):
if num + i <= n:
max_terms += 1
num = num + i
for terms in range(2,max_terms + 1):
for sample in list(combinations(list(range(1,n)),terms)):
if sum(sample) == n:
count += 1
print(count)
【问题讨论】:
-
首先,不要生成所有数字组合,然后过滤它们:只生成有效的组合。对于更大的数字,这变成了一个数学问题:不要生成组合,只需计算可以有多少组合。
-
这些只是分区,对吧? stackoverflow.com/questions/10035752/…
-
您的意思是“唯一的正数数”? “非零”数字将允许负数,这将允许对任何目标值进行无限数量的总和。
标签: python algorithm loops data-structures itertools