I have been studying algorithms and data structures off https://runestone.academy/runestone/static/pythonds/index.html, and I got to the part about dynamic programming and the classic minimum number of coins problem. Given a sum we have to figure out what is the minimum number of coins required to change it into coins from various denominations.
In the code the book proposes to solve the problem there are 2 lines whose role I can't figure out even if my life depended on it.
The code is here:
def recMC(coinValueList,change):
minCoins = change
if change in coinValueList:
return 1
else:
for i in [c for c in coinValueList if c <= change]:
numCoins = 1 + recMC(coinValueList,change-i)
if numCoins < minCoins:
minCoins = numCoins
return minCoins
print(recMC([1,5,10,25],63))
and I don't understand why we need this part:
if numCoins < minCoins:
minCoins = numCoins
return minCoins
I tried replacing all 3 lines with a single statement
return numCoins
And it seems to work just fine, except for when change == 0
. I don't think the way they wrote it in the book is meant to "protect" against an input of 0, since that can be handled even more trivially.
Why did they write it the way they did ?
ps: I am running it on python3.5 if it matters ...
cheers