2024-05-16 01:55:24 发布
网友
我希望能够找到所有不同的方法,一组数字(x)可以被求和成一个特定的值,但我甚至很难得到正确的基本情况
例如:
如果我有x=set(1,2,3,4,5),我想看看有多少种不同的方法可以用x中的数字求y=5的和:
我的递归函数将返回7,因为:
''' 5 4+1 3+2 3+1+1 2+2+1 2+1+1+1 1+1+1+1+1 ''' def recur(x,y): if y == x: v += 1 if y > x: v += 0 else: #call recursively
这不使用递归,而是itertools.combinations_with_replacement:
itertools.combinations_with_replacement
def all_combs(y, x=range(1, 5+1)): all_combs = [] for i in range(1, y+1): combs = combinations_with_replacement(x, i) all_combs.extend([comb for comb in combs if sum(comb) == y]) return all_combs combs = all_combs(5) # [(5,), (1, 4), (2, 3), (1, 1, 3), (1, 2, 2), (1, 1, 1, 2), (1, 1, 1, 1, 1)] num_combs = len(combs) # 7
这不使用递归,而是
itertools.combinations_with_replacement
:相关问题 更多 >
编程相关推荐