[英]All possible change combinations
I'm trying to output a list of lists with all possible combinations of change given an amount and coins.我正在尝试 output 一个列表列表,其中包含给定数量和硬币的所有可能的变化组合。 For example - given the amount 6 and the coins = [1,5,10] I would get:
例如 - 给定金额 6 和硬币 = [1,5,10] 我会得到:
[[1,1,1,1,1,1],
[1,5],
[5,1]]
I wrote something that prints the correct solution but I cannot figure out how to get the function to output the solutions in a list of lists format我写了一些打印正确解决方案的东西,但我不知道如何将 function 转换为 output 列表格式的解决方案
def possible_change(n,p=[],coins = [1,5,10]):
if n == 0:
print(p)
return p
else:
for c in coins:
if n - c >= 0:
possible_change(n-c,p+[c],coins=coins)
possible_change(6,coins=[1,5,10])
How to I get the function to return the actual lists?如何让 function 返回实际列表?
Instead of those print statements, simply populate a global list.而不是那些打印语句,只需填充一个全局列表。
sols = []
def possible_change(n,p=[],coins = [1,5,10]):
if n == 0:
global sols
sols.append(p)
else:
for c in coins:
if n - c >= 0:
possible_change(n-c,p+[c],coins=coins)
possible_change(6,coins=[1,5,10])
print(sols)
[[1, 1, 1, 1, 1, 1], [1, 5], [5, 1]]
You can try to add a total list to the function and return it if the n - c is less then 0 or if the for loop for c in coins:
is end您可以尝试将总列表添加到 function 并在 n - c 小于 0 或
for loop for c in coins:
def possible_change(n,p=[],coins = [1,5,10], total=[]):
if n == 0:
total.append(p)
else:
for c in coins:
if n - c >= 0:
print("c {}".format(c))
possible_change(n-c,p+[c],coins=coins)
else:
return total
return total
print(possible_change(6,coins=[1,5,10]))
Result结果
[[1, 1, 1, 1, 1, 1], [1, 5], [5, 1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.