周末无所事事,看见群里互动答题,刚好这两天在自学python,就顺便练练语法了。
题目:啤酒2元一瓶,4个瓶盖换一瓶,2个瓶子换一瓶,问10元钱能喝几瓶?
把生活中的事情转换成代码,我们首先要做的是找出事情的规律:
喝酒产生瓶盖和瓶子,瓶盖和瓶子又能换酒,酒又产生瓶盖和瓶子,如此不断循环,那么就很容易让人想到递归。只要对细节稍加控制,就可以完成计算了。
代码如下:
#!/usr/bin/env python3 # -*- coding:utf-8 -*- count = 0 surplus_bottleTop = 0 surplus_bottle = 0 def drinkAndSurplus(bottleTop, bottle): global count,surplus_bottleTop,surplus_bottle beers = 0 beers += bottleTop//4 beers += bottle//2 count += beers bottleTop = bottleTop%4 + beers bottle = bottle%2 + beers print(‘本次喝了%d瓶,剩余瓶盖%d个,剩余瓶子%d个‘%(beers, bottleTop, bottle)) if(bottleTop//4 > 0 or bottle//2 > 0): drinkAndSurplus(bottleTop, bottle) else: surplus_bottleTop = bottleTop surplus_bottle = bottle if __name__ == ‘__main__‘: money = 10 count, surplus_bottleTop, surplus_bottle = money//2, money//2, money//2 print(‘总共%d元钱,本次喝酒%d瓶,剩余瓶盖%d个,剩余瓶子%d个‘%(money,count,count,count)) drinkAndSurplus(surplus_bottleTop, surplus_bottle) print(‘总共喝了%d瓶,剩余瓶盖%d个,剩余瓶子%d个‘%(count,surplus_bottleTop,surplus_bottle))
执行结果如下:
python新手,大神勿喷!