I need some help because I think I'm lost. I've search before in this site and of course I've Google it, but believe me that if it was so simple to me, I haven't ask it at all, so please be kind to me. I'm new to python and coding isn't that easy to me.
Anyway, take a look at my code:
def coin_problem(price, cash_coins):
if (price < 0):
return []
if (price == 0):
return [[]]
options = []
for a_coin in cash_coins:
coins_minus_coin = cash_coins[:]
coins_minus_coin.remove(a_coin)
sub_coin_problem = coin_problem (price - a_coin, cash_coins)
for coin in sub_coin_problem:
coin.append(a_coin)
options.extend(sub_coin_problem)
return options
print coin_problem(4, [1, 2])
As you can see, I've tried to deal with the famous coin problem by recursion (and as I wrote before, I know many have already asked about this, I read their questions and the answers but I still couldn't understand the fully solutions).
This code was made by me, all of it. And now I'm stuck and confused. When the value of "price" is 4 and the value of "cash_coins" is [1,2] instead of returning something like this:
[1,1,1,1]
[2,2]
[2,1,1]
I get something more like:
[[1, 1, 1, 1], [2, 1, 1], [1, 2, 1], [1, 1, 2], [2, 2]]
the combination of "2" and the double "1" repeats 3 times instead of "1". I don't know what should I do in order to fix the problem or to improve my code so it will work better.
When you want to add a single item to a list, use append
. When you want to combine two lists together, use extend
.
Tips:
coins_minus_coin = cash_coins[:]
coins_minus_coin.remove(coin)
You never use this variable.
for i in sub_coins:
i.append(coin)
cash_coins_options.append(sub_coins)
You never use i
either. I'd guess you meant:
for i in sub_coins:
i.append(coin)
cash_coins_options.append(i)
That solves the problem of stange results, but your solution will still only find []
. Why? Your recursion can only stop on a return []
; it can't handle another fundamental case when you can tell the price using a single coin. Try adding at the top this simple condition:
# actually I changed my mind-
# I assume you're learning so try this one yourself :-)
This will cause your function to behave much better:
>>> print coin_problem(4, [1,2])
[[2, 1, 1], [1, 2, 1], [2, 2]]
which manages to produce correct answers (even though it duplicates some of them).
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.