numpy 如何将与价目表相关的产品数量表分配到客户订单表中

polhcujo  于 2024-01-08  发布在  其他
关注(0)|答案(2)|浏览(116)

我有一个分配问题-我有不同价格的产品供应,我需要按照先到先得的原则卖给人们,从最便宜的价格开始。
我有4个不同的列表/numpy数组:

  1. people = ['mark', 'greg', 'paul'] #This list is not needed, just for easier understanding
  2. orders = np.array([21, 6, 3], dtype=np.int64)
  3. quantity = np.array([16, 14], dtype=np.int64)
  4. price = np.array([30.5, 35.5], dtype=np.double)

字符串
订单的总和总是等于数量的总和。列表人员和订单是“连接”的,并根据降序排序:Mark想要购买21的数量,Greg想要购买6,Paul想要购买3。列表数量和价格也是“连接”的,并根据价格升序排序:有16个供应价格为30.5美元,14个供应价格为35.5美元。
计算每个买家的平均价格的最佳方法是什么?
一个简单的解决方案是:

  1. import numpy as np
  2. orders = np.array([21, 6, 3], dtype=np.int64)
  3. quantity = np.array([16, 14], dtype=np.int64)
  4. price = np.array([30.5, 35.5], dtype=np.double)
  5. start = 0
  6. supply = np.zeros((np.sum(quantity)), dtype=np.double)
  7. for i, quant in enumerate(quantity):
  8. idx = start + quant
  9. supply[start:idx] = price[i]
  10. start = idx
  11. print(supply)
  12. # [30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5 30.5
  13. # 30.5 30.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5 35.5
  14. # 35.5 35.5]
  15. fin = []
  16. start = 0
  17. for order in orders:
  18. idx = start + order
  19. fin.append(np.mean(supply[start:idx]))
  20. start = idx
  21. print(fin)
  22. # [31.69047619047619, 35.5, 35.5]


但这是可怕的,因为供应数组可能会变得非常大。我知道一定有一个很好的方法来处理numpy函数/索引,但我不知道如何做到这一点。最好的方法是什么?如果有人有任何关于如何处理浮点精度问题的提示,那也会很感激。(如何始终使:mean_prices * quantity == original_prices * quantities)

daolsyd0

daolsyd01#

您可以使用repeat扩展价格,并使用add.reduceat对每个块求和,然后通过除以项目数获得平均值:

  1. out = np.add.reduceat(np.repeat(price, quantity),
  2. np.r_[0, np.cumsum(orders)][:-1]
  3. ) / orders

字符串
输出量:

  1. array([31.69047619, 35.5 , 35.5 ])

u59ebvdq

u59ebvdq2#

您可以从两个列表中减少ordersquantity之间的最小值,并删除零和更小的值,直到订单为空

  1. orders = np.array([21, 6, 3], dtype=np.int64)
  2. quantity = np.array([16, 14], dtype=np.int64)
  3. price = np.array([30.5, 35.5], dtype=np.double)
  4. original_orders = orders.copy()
  5. fin = np.zeros(len(orders))
  6. while orders.size > 0:
  7. val = min(orders[0], quantity[0])
  8. orders[0] -= val
  9. quantity[0] -= val
  10. fin[-len(orders)] += price[-len(quantity)] * val
  11. orders = orders[orders > 0]
  12. quantity = quantity[quantity > 0]
  13. fin = np.around(fin / original_orders, 2)
  14. print(fin) # [31.69 35.5 35.5 ]
  15. # or if you want a list
  16. print(fin.tolist()) # [31.69, 35.5, 35.5]

字符串

展开查看全部

相关问题