简明扼要的"多少啤酒"问题?



我所在的位置

我想弄清楚回收每一瓶啤酒后,用10元人民币能买多少啤酒。我很清楚我在程序上做错了什么,但我并没有想到这是什么。我目前正在读第9章的《如何像计算机科学家一样思考:思考Python》。我觉得这对我来说应该是一个简单的程序,但我不知道如何在应用程序的回收部分循环。清洗和重复购买啤酒最简洁的方法是什么?

问题

基本上,一杯啤酒要2元人民币。2个箱子可获得1元人民币。4顶帽子可获得1元人民币。我的起价是10元人民币。我能买多少啤酒(回收所有的垃圾箱和盖子)?

#5 bottles 5 caps 
#= 3 rmb + 1 caps 1 bottles
#6th bottle bought 
#= 2rmb + 2 caps
#7th bottle bought 
#= 0rmb + 3 caps 1 bottles.
import math
def countbeers(rmb):
    beers = 0;
    caps = 0;
    bins = 0;
    bcost = 2;
    for i in range (0,rmb):
        beers += 1/2
    for i in range (0,math.floor(beers)):
        caps += 1
        bins += 1
        rmb = rmb - bcost
    for i in range (0,caps):
        rmb += 1/4
    for i in range (0,bins):
        rmb += 1/2
    #  if rmb > 2  what goes here, trying to loop back through
    return beers
print(countbeers(10))

第二次尝试

#5 bottles 5 caps 
#= 3 wallet + 1 caps 1 bottles
#6th bottle bought 
#= 2wallet + 2 caps
#7th bottle bought 
#= 0wallet + 3 caps 1 bottles.
import math
global beers
global caps
global bins
global bcost
beers = 0
caps = 0
bins = 0
bcost = 2
def buybeers(wallet):
    beers = 0
    for i in range (0,wallet):
        beers += 1/2
        wallet -= 2
    return beers
def drinkbeers(beers):
    for i in range (0,math.floor(beers)):
        caps += 1
        bins += 1
        wallet = wallet - bcost
    return wallet, caps, bins
def recycle(caps, bins):
    for i in range (0,caps):
        wallet += 1/4
    for i in range (0,bins):
        wallet += 1/2
    return wallet
def maxbeers(wallet):
    if wallet > 2:
        buybeers(wallet)
    if math.floor(beers) > 1:
        drinkbeers(beers)
    if caps > 4 | bins > 2:
        recycle(caps, bins)
        return wallet
wallet = int(input("How many wallet do you have?"))
maxbeers(wallet)
if wallet >= 2:
    maxbeers(wallet)
elif wallet < 2: 
    print(beers)

您的主要问题是没有循环。你从rmb买的每一瓶啤酒都会多给你一瓶,一顶。这个新的瓶子和盖子可能足以为你赢得另一个rmb,这可能足以再买一杯啤酒。您的实现在一定程度上处理了这一问题,因为您多次调用maxbeers,但如果您给它一卡车啤酒,即25656瓶,它将不会给出正确的答案。

如果你知道你有rmb的数量,你可以在纸上手工计算,并写下:

def maxbeers(rmb):
    return 7  # totally correct, I promise. Checked this by hand.

但这一点都不好玩。如果rmb25656呢?

假设我们可以交换:

2 bottles -> 1 rmb
4 caps -> 1 rmb
2 rmb -> 1 beer + 1 cap + 1 bottle

我们这样计算,通过模拟:

def q(rmb):
    beers = 0
    caps = 0
    bottles = 0
    while rmb > 0:
        # buy a beer with rmb
        rmb -= 2
        beers += 1
        caps += 1
        bottles += 1
        # exchange all caps for rmb
        while caps >= 4:
            rmb += 1
            caps -= 4
        # exchange all bottles for rmb
        while bottles >= 2:
            rmb += 1
            bottles -= 2
    return beers
for a in range(20):
    print("rmb:", a, "beers:", q(a))

然后我们可以买到20525瓶啤酒。

相关内容

  • 没有找到相关文章

最新更新