python - 回购函数的递归计数
问题描述
我正在尝试创建一个本质上是带有瓶子的回购程序的功能,规则如下
money -> 客户拥有的金额
BottleOwned -> 客户必须交换的瓶子数量
price -> 一瓶汽水的价格
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
你可以给它一个默认值,这样你就不需要在开始时指定它等于零(它总是如此)。
推荐阅读
- apache-nifi - Nifi - 在 MergeRecord 之前堆积的流文件
- css - 通过 Mac Web Inspector 对 CSS Safari IOS 进行故障排除时,用户代理样式表被锁定
- github - 如何将构建文件作为资产添加到 Github 中的发布?
- javascript - 电子剪贴板.writeHTML 不是函数
- vue.js - sinter 错误通过时如何向用户显示错误消息
- combobox - 我可以创建单例 vaadin 组合框组件吗?
- python - 在 REST API python 中将网站作为参数传递;“/”错误
- python - 如何在嵌入的 IPython shell 中实现自定义语句/宏?
- c++ - 如何在堆中声明静态 std::vector
- reactjs - 如何在 ReactDOM.render 中设置变量?