Change bottle algorithm problem


Soda bottle question: There is such an intellectual question: "A certain store stipulates that three empty soda bottles can be exchanged for one bottle of soda, and Xiao Zhang has ten empty soda bottles in his hand. How many bottles of soda can she drink at most? The answer is 5 bottles. , Tip: When there are 2 empty bottles at the end, you can ask the boss to borrow a bottle of soda, and then use 3 empty bottles to return a bottle of soda to the boss

If Xiao Zhang has n (n>1) empty soda bottles in his hand, how many soda bottles can be exchanged at most?

Problem analysis:
changing soda with an empty bottle will produce an empty bottle after drinking soda. The problem is abstracted out, that is, the continuous consumption process of the empty bottle. When we change to the last time the number of empty bottles is not enough to continue changing, there are only two situations:
1 : If there is 1 bottle left, the amount of soda can not be exchanged at this time, and the amount of soda obtained has been determined.
2: If there are 2 bottles remaining, you can ask the boss to borrow a bottle at this time, so the amount of soda obtained must be increased by 1 on the original basis.

Look at the following code:

Cycle version:

def exchange_bottle(n):
get_drink = 0
while n >= 3:
        # 换来饮料的数量,也是空瓶增加的数量
        bottle_add = n // 3
        # 用来换饮料消耗的空瓶数量
        bottle_reduce = bottle_add * 3
        # 一次交易后,当前空瓶的数量
        n = n + bottle_add - bottle_reduce
        #  一次交易后,得到饮料的数量
        get_drink += bottle_add
if n == 2:
        get_drink += 1
return get_drink

result = exchange_bottle(10)
print(result)

Recursive version:

def exchange_bottle(n,get_drink):
    if n == 2:
        get_drink += 1
        return get_drink
    if n == 1:
        return get_drink
    if n >= 3:
        # 换来饮料的数量,也是空瓶增加的数量
        bottle_add = n // 3
        # 用来换饮料消耗的空瓶数量
        bottle_reduce = bottle_add * 3
        # 一次交易后,当前空瓶的数量
        n = n + bottle_add - bottle_reduce
        #  一次交易后,得到饮料的数量
        get_drink += bottle_add
        return exchange_bottle(n,get_drink)

result = exchange_bottle(10,0)
print(result)

Class package version:

class GetDrink:
    def __init__(self,n):
        self.n = n
        self.get_drink = 0
        self.exchange_bottle()
    def exchange_bottle(self):
        if self.n == 2:
            self.get_drink += 1
            return self.get_drink
        if self.n == 1:
            return self.get_drink
        if self.n >= 3:
            bottle_add = self.n // 3
            bottle_reduce = bottle_add * 3
            self.n = self.n + bottle_add - bottle_reduce
            self.get_drink += bottle_add
            return self.exchange_bottle()
if __name__ == '__main__':
    result = GetDrink(10)
    print(result.get_drink)

Guess you like

Origin blog.51cto.com/12606610/2674432