【问题标题】:find and print each unique combination that sums to 100 and return a count of all such combinations for numbers between 1 and 100 [duplicate]查找并打印总和为 100 的每个唯一组合,并返回 1 到 100 之间数字的所有此类组合的计数 [重复]
【发布时间】:2013-08-05 18:57:01
【问题描述】:

数字范围是:1 到 100

我希望打印出介于 1 和 100 之间且总和等于 100 的每个 唯一 组合,最后是此类组合的计数 例如:

[1,99]
[1,2,97]
[1,2,3,4,5,85]

所以,我需要两件事:

  1. 打印每个有效组合
  2. 返回此类组合数的最终计数

这是我迄今为止尝试过的,但没有成功:

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)

【问题讨论】:

  • 我同意这是一个完全的骗局。它可以简化为链接的问题,但在这里 - 你有一个额外的限制。给定的数字集是 [1,2,..,100] - 而不是任意集合。

标签: python list recursion


【解决方案1】:

此代码不打印组合。

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2019-11-16
    • 2014-01-23
    • 1970-01-01
    • 2023-03-19
    • 2020-09-29
    • 2023-03-14
    相关资源
    最近更新 更多