以倍数递减? ; “没做什么”;创建一个除法或除法算法

时间:2016-01-08 19:12:18

标签: python increment

仍在研究啤酒问题。从头开始。我正试图不买半杯啤酒,所以这就是我开始的地方:

#import math

def buybeers(wallet):
    beers = 0
    for(int in xrange(0,wallet,2)) #xrange not defined
        beers += 1
        wallet -= 2
    return beers, wallet

wallet = int(input("How many wallet do you have?"))

print(buybeers(wallet))

我正在试图弄清楚如何以2美元的价格购买一杯啤酒并返还奇数美元。

第二次尝试,试图找到逻辑错误:

def buybeers(wallet):
    beers = 0
    for i in range(1,wallet,3):
        beers += 1
        wallet -= 3
    return beers, wallet

wallet = int(input("How many wallet do you have?"))

print(buybeers(wallet))

当我有14美元时会出现问题。我最终得到-1美元和5啤酒(我不应该喝啤酒和欠一美元)。虽然这是正确的,但一些便利店不接受标签。

最终提交(啤酒花费3美元)

def buybeers(wallet):
    beers = 0
    for i in range(1,wallet,3):
        if wallet >= 3:  #if you got enough for a beer, buy one.
            beers += 1
            wallet -= 3
    #else:
    #    pass #otherwise, "do nothing"/pass (it seems this is automated).
    return beers, wallet

wallet = int(input("How many wallet do you have?"))

print(buybeers(wallet))

1 个答案:

答案 0 :(得分:2)

你有一些丢失的括号,你的逻辑错了。假设您有$5且每个啤酒的费用为$2,那么您可以拥有2个啤酒并且剩余$1,但是,您的代码会为您提供3啤酒,现在你又欠了一美元。你可以通过使用除法和模数来简化这个

def buybeers(wallet):
    beers = wallet//2
    wallet = wallet % 2

    return beers, wallet

wallet = int(input("How many wallet do you have?"))

print(buybeers(wallet)) #5 as input

(2, 1)

修复你得到的语法错误

def buybeers(wallet):
    beers = 0
    for i in xrange(0,wallet,2):
        beers += 1
        wallet -= 2
    return beers, wallet

wallet = int(input("How many wallet do you have?"))

print(buybeers(wallet)) #5 as input

(3, -1)

由于你的for循环逻辑关闭,因此无法正确输出。