Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm studing the data structure and algorithm in python. Here is the classic problem of recursion involving making change with the fewest coins. Here are the codes. What I do not understand is line 2. why do we need minCoins = change? what does line 8-9 mean? can anyone helo explain that? thank you very much for help!

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

minCoins = change: minCoins is initialized with the value of change which is the maximum value that recMC can return as the minimum value of a coin is 1, assuming integer values of coins.

if change in coinValueList: return 1: base case 1 - if some coin has a value of that of change we just need to grab this 1 coin, thus returning 1

for i in [c for c in coinValueList if c <= change]:: The function then loops through all possible values of 1 single coin to

  numCoins = 1 + recMC(coinValueList,change-i): deduct the coin value i from change, add 1 coin to the number of coins needed which is recursively calculated for the leftover change (change-i). This works inductively from the 2 base cases

  if numCoins < minCoins: minCoins = numCoins inside this loop effectively assigns the smallest number of coins possible to minCoins

If change still had the initialized value of minCoins (implying no value c in coinValueList satisfies c <= change), this means that the number of coins needed is also the value of change, i.e. change 1-unit coins. This is base case 2 that is based on the pre-condition that the coin with value 1 is always available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...