I'm trying to output a list of lists with all possible combinations of change given an amount and coins. For example - given the amount 6 and the coins = [1,5,10] I would get:
[[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
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?
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
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.