如何消除此函数中的参数之一?

时间:2019-01-29 21:17:41

标签: python recursion

我想在代码下面消除第三个参数,它只是一个空数组,我认为我应该能够在函数本身内将其创建为局部变量。

作为奖励,我也想将其构建为单个函数,尽管我认为无法使用当前的代码递归结构来实现。

我尝试创建一个空数组作为局部变量(请参见注释掉的整数列表)

我还尝试创建一个count变量,以使找到的每个组合递增(请参见注释掉的count变量)

def count_combinations(number, integers_available, integers):

    coin_set = []
    # integers = []
    # count = 0

    if sum(integers) == number:
        coin_set.append(integers)
        # count += 1

    elif sum(integers) > number:
        pass

    elif integers_available == []:
        pass

    else:
        for c in count_combinations(number, integers_available[:], integers + [integers_available[0]]):
            coin_set.append(c)
            # count += 1
        for c in count_combinations(number, integers_available[1:], integers):
            coin_set.append(c)
            # count += 1

    # return count += 1
    return coin_set

def count_total(number, integers_available, integers):
    return len(count_combinations(number, integers_available, integers))

# Testing the code
number = 15
integers_available = [1, 5, 10]
print(count_total(number, integers_available, []))

我希望得到相同的结果,但是函数中的参数更少,因为其中一个参数将改为切换为局部变量。

2 个答案:

答案 0 :(得分:3)

正如评论中所讨论的那样,动态编程方法在这里可能更像Python。

from collections import Counter

def ways(total, coins=(1,2,5,10,20,50,100)):
    counts = [[Counter()]] + [[] for _ in range(total)]
    for coin in coins:
        for i in range(coin, total + 1):
            counts[i] += [c + Counter({coin: 1}) for c in counts[i-coin]]
    return counts[total]

演示:

>>> ways(15, coins=(1,5,10))
[Counter({1: 15}),
 Counter({1: 10, 5: 1}),
 Counter({1: 5, 5: 2}),
 Counter({5: 3}),
 Counter({1: 5, 10: 1}),
 Counter({5: 1, 10: 1})]
>>> len(ways(15, coins=(1,5,10)))
6

答案 1 :(得分:0)

在不考虑算法或代码目标的情况下,可以通过以下方法将其整理为单个函数并为integers参数提供默认值,从而对其进行整理:

def count_total(number, integers_available):
    def count_combinations(number, integers_available, integers=[]):
        coin_set = []
        # integers = []
        # count = 0

        if sum(integers) == number:
            coin_set.append(integers)
            # count += 1

        elif sum(integers) > number:
            pass

        elif integers_available == []:
            pass

        else:
            for c in count_combinations(number, integers_available[:], integers + [integers_available[0]]):
                coin_set.append(c)
                # count += 1
            for c in count_combinations(number, integers_available[1:], integers):
                coin_set.append(c)
                # count += 1

        # return count += 1
        return coin_set

    return len(count_combinations(number, integers_available))

# Testing the code
number = 15
integers_available = [1, 5, 10]
print(count_total(number, integers_available))