Your main problem is that you are not looping. Every beer you bought from rmb
gives you one more bottle, and one more cap. This new bottle and cap might be enough to earn you another rmb
, which might be enough for another beer. Your implementation handles this to a limited extent, since you call maxbeers multiple times, but it will not give the correct answer if you give it a truckload of beers, i.e. 25656 bottles.
If you know the number of rmb
you have, you can do the calculation by hand on paper and write this:
def maxbeers(rmb):
return 7 # totally correct, I promise. Checked this by hand.
but that’s no fun. What if rmb
is 25656
?
Assuming we can exchange:
2 bottles -> 1 rmb
4 caps -> 1 rmb
2 rmb -> 1 beer + 1 cap + 1 bottle
we calculate it like this, through simulation:
def q(rmb):
beers = 0
caps = 0
bottles = 0
while rmb > 0:
# buy a beer with rmb
rmb -= 2
beers += 1
caps += 1
bottles += 1
# exchange all caps for rmb
while caps >= 4:
rmb += 1
caps -= 4
# exchange all bottles for rmb
while bottles >= 2:
rmb += 1
bottles -= 2
return beers
for a in range(20):
print("rmb:", a, "beers:", q(a))
Then we can buy 20525 beers.
2
solved The concise ‘how many beers’ issue?