郭冬临韩雪小品《没那么简单》!郭冬临到底喝了多少瓶水?

今天情人节,早上和丈母娘看了小品《没那么简单》,小品表演中郭冬临为了教儿子做数学题,和韩雪扮演成客户和买家,汽水2块一瓶,2个瓶盖可以换一瓶汽水,4个空瓶也能换一瓶汽水,

问最多能喝多少瓶。直接拿出mbp,打开Sublime Text。

money: float = 10 # money you have
drink: float = 2 # drink price
capNumber: int = 2 # bottom caps that could exchange drinks
bottomNumber: int = 4 # bottoms that could exchange drinks
x: int = 0 # drinked number

def capAndBottomLeft(capNum: int, bottomNum: int) -> tuple:
	return (capNum % capNumber, bottomNum % bottomNumber)

def exchangeDrinkNum(capNum: int, bottomNum: int) -> int:
	return int(capNum / capNumber) + int(bottomNum / bottomNumber)

if __name__ == '__main__':
	capNum = 0
	bottomNum = 0
	drinkNum = int(money / drink)
	x += drinkNum
	capNum += drinkNum
	bottomNum += drinkNum
	while exchangeDrinkNum(capNum, bottomNum) > 0:
		drinkNum = exchangeDrinkNum(capNum, bottomNum)
		x += drinkNum
		capNum, bottomNum = capAndBottomLeft(capNum, bottomNum)
		capNum += drinkNum
		bottomNum += drinkNum
	print(x)

今早学习了一下golang语言,来到公司试一试:

package main

import "fmt"

const (
	exchangeableCapNum    = 2
	exchangeableBottomNum = 4
)

func main() {
	money := 10
	water := 2

	x := int32(money / water)
	capNum := x
	bottomNum := x
	for exchangeable(capNum, bottomNum) {
		m := int32(capNum / exchangeableCapNum)
		n := int32(bottomNum / exchangeableBottomNum)
		capNum %= exchangeableCapNum
		bottomNum %= exchangeableBottomNum
		exchangeWaterNum := add(m, n)
		capNum += exchangeWaterNum
		bottomNum += exchangeWaterNum
		x += int32(exchangeWaterNum)
	}
	fmt.Println(x)
}

func exchangeable(capNum, bottomNum int32) bool {
	return capNum >= 2 || bottomNum >= 4
}

func add(a, b int32) int32 {
	return a + b
}

你可能感兴趣的:(算法)