gpt4 book ai didi

python - 如何获得其权重受 Python 3.6 中的变量限制的列表的加权平均值

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:08 26 4
gpt4 key购买 nike

我希望标题有意义。我想要实现的是获得鞋子的加权平均价格,这些鞋子的价格不同,数量也不同。所以我有例如:

list_prices = [12,12.7,13.5,14.3]
list_amounts = [85,100,30,54]
BuyAmount = x

我想知道我的加权平均价格,以及我为每双鞋支付的最高价格如果我买了 x 数量的鞋子(假设我想先买最便宜的)

这是我现在拥有的(我使用 numpy):

    if list_amounts[0] >= BuyAmount:
avgprice = list_prices[0]
highprice = list_prices[0]

elif (sum(list_amounts[0: 2])) >= BuyAmount:
avgprice = np.average(list_prices[0: 2], weights=[list_amounts[0],BuyAmount - list_amounts[0]])
highprice = list_prices[1]

elif (sum(list_amounts[0: 3])) >= BuyAmount:
avgprice = np.average(list_prices[0: 3], weights=[list_amounts[0],list_amounts[1],BuyAmount - (sum(list_amounts[0: 2]))])
highprice = list_prices[2]

elif (sum(list_amounts[0: 4])) >= BuyAmount:
avgprice = np.average(list_prices[0: 4], weights=[list_amounts[0],list_amounts[1],list_amounts[2],BuyAmount - (sum(list_amounts[0: 3]))])
highprice = list_prices[3]

print(avgprice)
print(highprice)

此代码有效,但可能过于复杂和庞大。特别是因为我希望能够处理包含 20 多个项目的金额和价目表。

执行此操作的更好方法是什么?

最佳答案

你确实是对的,你的代码缺乏灵 active 。但在我看来,您是从一个有效的角度来看问题的,但还不够笼统。

换句话说,您的解决方案实现了这个想法:“让我先检查 - 给定每个价格的可用数量(我在数组中进行了漂亮的排序) - 我必须从哪些不同的卖家那里购买,然后再做所有的计算。”

一个更灵活的想法可以是:“让我尽可能多地从更便宜的商品开始购买。我会在订单完成时停止,并逐步计算数学”。这意味着您构建一个迭代代码,逐步累积总花费金额,并在完成后计算每件的平均价格和最高价格(即您订购列表中最后访问的价格)。

将这个想法转化为代码:

list_prices = [12,12.7,13.5,14.3]
list_amounts = [85,100,30,54]
BuyAmount = x

remaining = BuyAmount
spent_total = 0
current_seller = -1 # since we increment it right away

while(remaining): # inherently means remaining > 0
current_seller += 1
# in case we cannot fulfill the order
if current_seller >= len(list_prices):
# since we need it later we have to restore the value
current_seller -= 1
break
# we want either as many as available or just enough to complete
# BuyAmount
buying = min([list_amounts[current_seller], remaining])
# update remaining
remaining -= buying
# update total
spent_total += buying * list_prices[current_seller]

# if we got here we have no more remaining or no more stock to buy

# average price
avgprice = spent_total / (BuyAmount - remaining)

# max price - since the list is ordered -
highprice = list_prices[current_seller]

print(avgprice)
print(highprice)

关于python - 如何获得其权重受 Python 3.6 中的变量限制的列表的加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com