[英]Finding best combinations of consecutive and same numbers in a list starting with a group of at least 3
[英]Finding the best combinations
我正在尋找解決以下問題的方法。
假設我有這個產品網格。
table = [{'Products': 'Prod1', 'Unit1': 32, 'Unit2': 32, 'Unit3': 27, 'Unit4': 15 },
{'Products': 'Prod2', 'Unit1': 35, 'Unit2': 12, 'Unit3': 19, 'Unit4': 29 },
{'Products': 'Prod3', 'Unit1': 37, 'Unit2': 36, 'Unit3': 36, 'Unit4': 19 },
{'Products': 'Prod4', 'Unit1': 16, 'Unit2': 15, 'Unit3': 18, 'Unit4': 31 },
{'Products': 'Prod5', 'Unit1': 14, 'Unit2': 32, 'Unit3': 20, 'Unit4': 33 },
{'Products': 'Prod6', 'Unit1': 10, 'Unit2': 33, 'Unit3': 28, 'Unit4': 36 },
{'Products': 'Prod7', 'Unit1': 18, 'Unit2': 22, 'Unit3': 27, 'Unit4': 30 },
{'Products': 'Prod8', 'Unit1': 11, 'Unit2': 13, 'Unit3': 20, 'Unit4': 26 }]
df = pd.DataFrame(table)
每個值都反映了我通過銷售此產品獲得的最大收益。 例如,出售2個prod1
單位,我將獲得32美元。 對於每種產品,我最多可以賣4個單位。 我總共可以賣出16個單位(4 * 4)。 我的目標是最大化總收入。 在給出的示例中,我將銷售以下組合以最大化我的收入:
{prod1: 2 units (32),
prod2: 1 unit (35),
prod3: 1 unit (37),
prod4: 4 units (31),
prod5: 4 units (33),
prod6: 4 units (36)}
我的問題是,我如何通過算法來制定它?
簡單的解決方案是測試所有選項並確定提供最大收益的選項。
可以使用itertools.product
生成所有選項:
from itertools import product
options = product(range(5), repeat=8)
一個人可以賣出每個產品的0,1,2,3或4個單位,所以我使用range(5)
作為第一個參數,有8個產品,所以我使用repeat=8
。
但是,我們不希望最大化銷售的單位數量,但是當銷售16個或更少單位時的收入。 在這種情況下,我使用帶key
功能的max
。 如果銷售的單位超過16個,則鍵功能返回負值,否則根據單詞列表和已售單位數檢查收入是多少:
def total_revenue(sales):
if sum(sales) > 16: # discard the revenue if more than 16 units are sold.
return -1
else:
# Sum the revenue based on the sales and the values in the table.
sum_ = 0
for idx, num in enumerate(sales):
if num:
sum_ += table[idx]['Unit{}'.format(num)]
return sum_
maximized_revenue = max(options, key=total_revenue)
print(maximized_revenue)
# (1, 1, 1, 4, 2, 2, 1, 4)
這是一個元組,仍然需要轉換為所需的字典:
{'prod{}'.format(idx+1): num for idx, num in enumerate(maximized_revenue)}
# {'prod1': 1,
# 'prod2': 1,
# 'prod3': 1,
# 'prod4': 4,
# 'prod5': 2,
# 'prod6': 2,
# 'prod7': 1,
# 'prod8': 4}
仍有改進的余地,因為product
產生許多不必要的價值(超過16件商品)。 您可以使用repeat
參數創建一個與product
類似的自定義生成器,但是當已售出超過16個單元時,不會生成解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.