脑力小运动 预防痴呆的小问题
2元一瓶酒,2个空瓶换一瓶,4个瓶盖换一瓶 问10块钱买几瓶酒??
使用面向对象的方法
class Change:
def __init__(self,money):
self.money=money
self.beer=money//2
self.bottle=0
self.cap=0
self.count=0
def ping(self):
new_beer=self.bottle//2
self.beer+=new_beer
self.bottle-=(new_beer*2)
def gai(self):
new_beer=self.cap//4
self.beer+=new_beer
self.cap-=(new_beer*4)
def drink(self):
self.bottle+=self.beer
self.cap+=self.beer
self.count+=self.beer
self.beer=0
def run(self):
while self.beer>0 or self.bottle>=2 or self.cap>=4:
self.drink()
self.ping()
self.gai()
return '喝了%d瓶酒,剩余%d个瓶子,剩余%d个盖子'%(self.count,self.bottle,self.cap)
person=Change(10)
print(person.run())
使用递归的方法
count = 0
yu_cap = 0
yu_bottle = 0
def drink(cap, bottle):
global count,yu_cap,yu_bottle
beers = 0
beers += cap//4
beers += bottle//2
count += beers
cap = cap%4 + beers
bottle = bottle%2 + beers
print('本次喝了%d瓶,剩余瓶盖%d个,剩余瓶子%d个'%(beers, cap, bottle))
if(cap//4 > 0 or bottle//2 > 0):
drink(cap, bottle)
else:
yu_cap = cap
yu_bottle = bottle
if __name__ == '__main__':
money = 10
count, yu_cap, yu_bottle = money//2, money//2, money//2
print('总共%d元钱,本次喝酒%d瓶,剩余瓶盖%d个,剩余瓶子%d个'%(money,count,count,count))
drink(yu_cap, yu_bottle)
print('总共喝了%d瓶,剩余瓶盖%d个,剩余瓶子%d个'%(count,yu_cap,yu_bottle))