I am learning to write recursive functions in python. I wrote this to solve for the number of coins due back in making change for any amount (ignores any paper money, i.e. a quarter is the highest denomination possible).
While I know there is probably a better algorithm for this, right now I am just interested in why this one I wrote doesn't work. If I input anything other than a coin's exact amount, it returns an error saying recursive depth exceeded.
import sys
import math
def get_change(m, coin_count):
if m == 0:
return coin_count
else:
if m >= 0.25:
coin_count += math.floor(m / 0.25)
m = m % 0.25
elif m >= 0.1:
coin_count += math.floor(m / 0.1)
m = m % 0.1
elif m >= 0.05:
coin_count += math.floor(m / 0.1)
m = m % 0.05
elif m >= 0.01:
coin_count += math.floor(m / 0.01)
m = m % 0.01
return get_change(m, coin_count)
m = float(input())
coin_count = 0
print(get_change(m, coin_count))
Here is corrected code from the helpful comments. Works now. Decided to change format so decimals are not an issue:
def get_change(m, coin_count):
if m < 1:
return coin_count
else:
if m >= 25:
coin_count += math.floor(m / 25)
m = m % 25
elif m >= 1:
coin_count += math.floor(m / 10)
m = m %1
elif m >= 5:
coin_count += math.floor(m / 5)
m = m % 5
elif m >= 1:
coin_count += math.floor(m / 1)
m = m % 1
return get_change(m, coin_count)
m = int(input())
coin_count = 0
print(get_change(m, coin_count))