我想创建一个函数,本质上是一个用瓶子回购的程序,规则如下
金钱 -> 客户拥有的金钱数额。
bottlesOwned -> 客户需要更换的瓶子数量。
一瓶汽水的价格
exchangeRate -> 兑换率,用元组表示。第一个元素是可以兑换的一组瓶子的最小尺寸。 第二个参数是一组瓶子收到的退款。
客户在一次访问商店时可以退还任意多组瓶子,但退还的瓶子总数必须是 exchangeRate 第一个元素的倍数。
函数必须输出客户在所有行程中能够购买的瓶子总数,直到客户的钱用完为止。
def lightningBottle(money, bottlesOwned, price, exchangeRate):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
这是我所得到的最多的信息,但我无法理解如何在不使用全局变量的情况下让瓶子购买的计数器滴答作响(我不能使用全局变量,因为它不会在并发测试中重置,并且提供了错误的答案)。
你已经很接近了。你只需要 bottlesbought
作为你的函数的一个参数,你可以给它一个默认值,这样你就不需要在开始时指定它等于零(它总是这样)。
def lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought=0):
if bottlesOwned >= exchangeRate[0]:
bottlesOwned -= exchangeRate[0]
money += exchangeRate[1]
if money >= price:
bottlesOwned += 1
bottlesbought += 1
money -= price
return lightningBottle(money, bottlesOwned, price, exchangeRate, bottlesbought)
else:
print ("we bought",bottlesbought,"bottles")
return bottlesbought
你可以给它一个默认值,这样你就不需要在一开始就指定它等于0(它总是等于0)。