python - 计算价格上涨的商品总价太慢
问题描述
我正在创建一个简单的闲置游戏,您可以在其中购买东西并且购买的每件商品的价格都会上涨。我有一个按钮,允许玩家单击一次即可购买最大数量。这很好用,但是计算总价非常慢,因为我是在一个 while 循环中这样做的。我怎样才能简化这个?
var accumulatedPrice = 0.0
var maxMultiplier = 0
while accumulatedPrice <= allMyMoney:
var assetPrice = 4.8
var priceGrowth = 1.12
priceGrowth = pow(priceGrowth, asset.currentAmount+maxMultiplier-1)
assetPrice *= priceGrowth
accumulatedPrice += assetPrice
maxMultiplier += 1
我稍微简化了我的代码,它不是用任何特定的语言编写的。我实际上使用了一个大数字类来允许极高的数字,但数学与上面相同。当 maxMultiplier 最终变高时,它会变慢。
解决方案
我似乎不明白这个问题。我已经用 64 位最大整数 ( 9223372036854775807
) 进行了尝试,这花了我2.7418136596679688e-05
几秒钟的时间。
from time import time
import sys
all_money = sys.maxsize
asset_price = 1.8
price_growth = 1.12
next_asset_price = asset_price ** price_growth
amount = 0
start = time()
while all_money > 0:
if all_money - next_asset_price < 0:
print(f"Total: {amount}")
break
all_money -= next_asset_price
amount += 1
next_asset_price = next_asset_price ** price_growth
print(f"\nTotal runtime: {time()-start}")
推荐阅读
- python - Python中具有数量约束的分配最低成本
- javascript - 将类绑定到另一个类的实例
- python - 试图从网络上获取链接
- swift - 出现错误“无法读取数据,因为它丢失了。” 在使用 alamofire 和 swift 获取数据期间
- javascript - 如何通过 ajax 和 javascript 从数据库中打印行?
- python-3.x - 如何删除边框并在栏本身中添加名称
- node.js - 安装 Angular / 最新版本
- ansible - 如何通过在ansible playbook中测试与`lookup('dig', ...)`的(不)相等性来习惯性地过滤主机名列表
- wix - 如何使用 Wix Burn 安装根证书?
- php - PHP - 更改变量名