题:
1元钱一瓶汽水,喝完之后两个空瓶换一瓶汽水。 问:若你有N元钱,你最多能喝多少瓶汽水?
两种情况:1)不可向老板借个空瓶。2)可向老板借个空瓶。
# python -version : python3
# 苏打水问题:递归(不可借空瓶),一块钱或者两个瓶子等价一块钱
def SodaWaterNoLend(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n % 2 == 0: # 大于等于2的偶数钱。偶数钱,喝完后,可以再兑换一半的瓶数饮料。
return n + SodaWaterNoLend(n//2)
else:
return n + 1 + SodaWaterNoLend(n//2)
# 苏打水问题:递归(可借空瓶),一块钱或者两个瓶子等价一块钱
def SodaWaterLend(n):
if n == 0: # 没钱
return 0
# elif n == 1: # 1块钱
# return 2
elif n % 2 == 0: # 大于等于2的偶数钱。偶数钱,喝完后,可以再兑换一半的瓶数饮料。
return n + SodaWaterLend(n // 2)
else: # 大于等于 1 的奇数钱。奇数钱,喝完后,再兑换一半的瓶数饮料( 1块钱 例外),同时还剩下一个空瓶,可以向老板借个空瓶,两个空瓶兑换一瓶饮料,喝完后再归还老板空瓶。
return n + 1 + SodaWaterLend(n // 2)
# 苏打水问题:归纳公式(可借空瓶),一块钱或者两个瓶子等价一块钱。规律、循环、公式
def LoopLend(n):
return 2*n
# 苏打水问题:归纳公式(不可借空瓶),一块钱或者两个瓶子等价一块钱。规律、循环、公式
def LoopNoLend(n):
if n == 0: # 没钱
return 0
else:
return 2 * n - 1
def main():
print('*** Soda Water Lend:Recursion ***')
for i in range(5):
# Money = int(input('Please input money: '))
Money = i
soda_total = SodaWaterLend(Money)
print(str(i)+' 元钱'+'总共能喝苏打水瓶数为: '+str(soda_total))
print('*** Soda Water No Lend:Recursion ***')
for i in range(5):
# Money = int(input('Please input money: '))
Money = i
soda_total = SodaWaterNoLend(Money)
print(str(i)+' 元钱'+'总共能喝苏打水瓶数为: '+str(soda_total))
print('*** Soda Water Lend:Loop ***')
for i in range(5):
# Money = int(input('Please input money: '))
Money = i
soda_total = LoopNoLend(Money)
print(str(i)+' 元钱'+'总共能喝苏打水瓶数为: '+str(soda_total))
print('*** Soda Water NO Lend:Loop ***')
for i in range(5):
# Money = int(input('Please input money: '))
Money = i
soda_total = LoopLend(Money)
print(str(i)+' 元钱'+'总共能喝苏打水瓶数为: '+str(soda_total))
if __name__ == '__main__':
main()
运行结果:
大神博客讲的很有意思,很好理解,慢慢看~~~
https://blog.csdn.net/Qizhi_Hu/article/details/106936057?utm_source=app
Game Over~~~