校正递归生成器代码

时间:2017-06-16 13:12:04

标签: python python-3.x recursion generator

首先,感谢您的帮助。我有这个递归代码,用于计算硬币列表和给定金额的变化方式。我需要编写一个递归生成器代码,它代表了每次迭代变更资金的方式。例如,如果您获得5的金额和[1,2,3]硬币列表,那么这将是输出:

for e in change_gen(5,[1,2,3]):
     print(e)

 [1, 1, 1, 1, 1]
 [1, 1, 1, 2]
 [1, 2, 2]
 [1, 1, 3]
 [2, 3]

这是我尝试过的: 怎么了?

使用像binom和pascal这样的algoritem的代码{n \ choose k} = {n-1 \ choose k-1} + {n-1 \ choose k}

def change_gen(amount, coins):
    if amount == 0:
       yield []
    elif not (amount < 0 or coins == []):
       g = change_gen(amount, coins[:-1])
       f = change_gen(amount - coins[:-1],coins)
       while True:
            yield Next(g)
       yield coins[:-1].extend(next2(f))

1 个答案:

答案 0 :(得分:0)

你的递归是正确的:用硬币减少和减少金额来递减。这是一个更正的实现,添加了测试用例。

def change_gen(amount, coins):
    if amount == 0:
       yield []
    elif amount > 0 and coins:
        coin = coins.pop()
        yield from change_gen(amount, coins)
        coins.append(coin)
        for lis in change_gen(amount - coin, coins):
            lis.append(coin)
            yield lis

changes = list(change_gen(5, [1,2,3]))
print(changes)
assert changes == [
 [1, 1, 1, 1, 1],
 [1, 1, 1, 2],
 [1, 2, 2],
 [1, 1, 3],
 [2, 3],
]

断言通过。