タイトルが意味をなすといいのですが。私が達成しようとしているのは、さまざまな価格でさまざまな金額で入手できる靴の加重平均価格を取得することです。だから私は例えば持っています:
list_prices = [12,12.7,13.5,14.3]
list_amounts = [85,100,30,54]
BuyAmount = x
加重平均価格と、靴1足あたりに支払った最高価格を知りたい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以上のアイテムで金額と価格のリストを処理できるようにしたいので。
これを行うためのより良い方法は何ですか?
cumsum
これらのスライスされた合計を置き換えargmax
、これらのIF-case
操作のスライス制限を設定するために使用される適切なインデックスを取得するために使用する一般的なベクトル化されたソリューションを次に示します-
# Use cumsum to replace sliced summations - Basically all those
# `list_amounts[0]`, `sum(list_amounts[0: 2]))`, `sum(list_amounts[0: 3])`, etc.
c = np.cumsum(list_amounts)
# Use argmax to decide the slicing limits for the intended slicing operations.
# So, this would replace the last number in the slices -
# list_prices[0: 2], list_prices[0: 3], etc.
idx = (c >= BuyAmount).argmax()
# Use the slicing limit to get the slice off list_prices needed as the first
# input to numpy.average
l = list_prices[:idx+1]
# This step gets us the weights. Now, in the weights we have two parts. E.g.
# for the third-IF we have :
# [list_amounts[0],list_amounts[1],BuyAmount - (sum(list_amounts[0: 2]))]
# Here, we would slice off list_amounts limited by `idx`.
# The second part is sliced summation limited by `idx` again.
w = np.r_[list_amounts[:idx], BuyAmount - c[idx-1]]
# Finally, plug-in the two inputs to np.average and get avgprice output.
avgprice = np.average(l,weights=w)
# Get idx element off list_prices as the highprice output.
highprice = list_prices[idx]
当社は、連結ステップ(とを削除するために最適化を進めることができますnp.r_
)とを取得avgprice
ので、同様に、 -
slice1_sum = np.multiply(list_prices[:idx], list_amounts[:idx]).sum()
# or np.dot(list_prices[:idx], list_amounts[:idx])
slice2_sum = list_prices[idx]*(BuyAmount - c[idx-1])
weight_sum = np.sum(list_amounts[:idx]) + BuyAmount - c[idx-1]
avgprice = (slice1_sum+slice2_sum)/weight_sum
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加