注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
初学python,一道题目如下: 用 1, 5, 10, 25美分凑1美元,问有多少种凑法(242种) 。答案用generator写的,确认能跑出答案。但我对第二个for loop不太明白,为啥又在make_change函数里loop了呢? 没见过这种操作,有高手能给说说吗
def make_change(amount, coins=[1,5,10,25], hand=None):
hand=[] if hand is None else hand
if amount==0:
yield hand
for coin in coins:
if coin > amount or (len(hand)>0 and hand[-1] < coin):
continue
for result in make_change(amount-coin, coins=coins, \
hand=hand+[coin]):
yield result
for way in make_change(100,coins=[1,5,10,25], hand=None):
print(way)
|