gpt4 book ai didi

python - 难以理解代码片段的流程

转载 作者:行者123 更新时间:2023-11-28 21:13:41 24 4
gpt4 key购买 nike

我很难理解下面的代码。它计算用可用面额('coins')的硬币赚取金额('n')的方法的数量

def change(n, coins_available, coins_so_far):
if sum(coins_so_far) == n:
yield coins_so_far
elif sum(coins_so_far) > n:
pass
elif coins_available == []:
pass
else:
for c in change(n, coins_available[:], coins_so_far+[coins_available[0]]):
yield c
for c in change(n, coins_available[1:], coins_so_far):
yield c

n = 15
coins = [1, 5, 10, 25]

solutions = [s for s in change(n, coins, [])]
for s in solutions:
print s

输出:

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5]
[1, 1, 1, 1, 1, 5, 5]
[1, 1, 1, 1, 1, 10]
[5, 5, 5]
[5, 10]

我明白第一次迭代是如何导致 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 我不明白[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 转换为 [1, 1, 1, 1, 1, 1, 1, 1 , 1, 1, 5]我相信 'coins_so_far' 在 'coins_available' 持有 [ 5,10,25]

非常感谢任何帮助。谢谢

最佳答案

英语:

How to determine the ways to make change(for n cents, using coins in
coins_available denominations, and which include a pile of coins_so_far):
If the coins_so_far sum to n:
That is the unique way to do it.
(Because we've already added enough coins to the pile to make
the desired amount of change.)
Otherwise, if the coins_so_far sum to more than n:
There are no ways to do it.
(Because there's already too much in our pile; we can't fix
this by adding more.)
Otherwise, if there are no coins_available:
There are no ways to do it.
Otherwise:
(To make change for the rest of the pile, we either *do* add
at least one more of the smallest possible coin, or we *don't*.)
Every way to make change(for n cents, using the same
coins_available, and which includes the coins_so_far
as well as the first of the coins_available):
Is one of the ways to do it.
(Try adding a coin of the smallest denomination to the pile,
and then figure out all the ways to make up the rest of the
change. This finds the ways that do add the small coin.)
Every way to make change(for n cents, using all the
coins_available except the first, and including the
coins_so_far):
Is also a way to do it.
(Find the ways that don't add the smallest coin denomination,
by excluding it from the denominations we'll consider, and
using the same process.)

关于python - 难以理解代码片段的流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com