数字范围是:1到100
我希望打印出1到100之间的每个 唯一 组合,其总和等于100,最后是这种组合的计数 例如:
[1,99]
[1,2,97]
[1,2,3,4,5,85]
所以,我需要两件事:
这是我到目前为止所尝试的并没有成功:
count = 0
def get_count(target, data_range, current_sum):
global count
for num in data_range:
current_sum += num
if current_sum > target:
break
elif current_sum == target:
count += 1
current_sum = 0
elif current_sum < target:
get_count(target, range(num + 1, 101), current_sum)
return count
get_count(target = 100, data_range = range(1,101), current_sum = 0)
答案 0 :(得分:0)
此代码不会打印组合。
def memoized(f):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
return wrapper
def get_count(target):
@memoized
def f(target, cur):
if target < 0: return 0
if target == 0: return 1
return sum(f(target - n, n + 1) for n in range(cur, target + 1))
return f(target, 1)
print(get_count(100))