基于回购函数的递归计数

2024-05-23 21:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,它本质上是一个带瓶子的回购程序,规则如下

金钱->;客户拥有的金额

瓶装种子->;客户必须更换的瓶子数量

价格->;一瓶汽水的价格

汇率->;以元组表示的汇率。第一个元素是可以交换的瓶子组的最小尺寸。第二个论点是一组瓶子的退款

客户可以在一次访问商店时退还任意数量的瓶子,但退还的瓶子总数必须是交换率第一要素的倍数

该功能必须输出客户在所有行程中能够购买的瓶子总数,直到客户的钱用完为止

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

这是我所能做到的,但我无法想出如何在不使用全局变量的情况下使瓶装水计数器正常工作(我不能使用全局变量,因为它不会在并发测试中重置,并提供错误的答案)


Tags: gt瓶子数量客户returnifexchangerate汇率
1条回答
网友
1楼 · 发布于 2024-05-23 21:35:29

你很接近。您只需要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

您可以给它一个默认值,这样就不需要在开始时指定它等于零(它总是等于零)

相关问题 更多 >