Python 伪代码优化利润
我目前正在处理一个问题,希望在思考过程中得到帮助,或者在代码中得到更正。我的函数主要有三个参数n people、maxweight和items。项目位于二维列表中,表示ID、价格和重量。例如[项目A、20、50],[项目B、30、60] 我必须返回每个n人的2D物品清单,每个人携带的物品都经过价格优化,但以公平的方式分配。它也不能超过最大重量。所以,如果n是3,那么第三个人不应该只携带价格低的物品,而第一个人只携带价格高的物品,在一定程度上应该是偶数。例如,如果n为2,项目列表长度为6,则人员1和2携带的项目结果可能为:Python 伪代码优化利润,python,list,algorithm,Python,List,Algorithm,我目前正在处理一个问题,希望在思考过程中得到帮助,或者在代码中得到更正。我的函数主要有三个参数n people、maxweight和items。项目位于二维列表中,表示ID、价格和重量。例如[项目A、20、50],[项目B、30、60] 我必须返回每个n人的2D物品清单,每个人携带的物品都经过价格优化,但以公平的方式分配。它也不能超过最大重量。所以,如果n是3,那么第三个人不应该只携带价格低的物品,而第一个人只携带价格高的物品,在一定程度上应该是偶数。例如,如果n为2,项目列表长度为6,则人员1
[[Item A, Item C, Item F], [Item B, Item E]]
其中不添加D,因为它将超过重量
这就是我到目前为止的想法:
def listofItems(n, maxweight, items):
sort the 2d lists of items according to desc prices
result = n * [[]] #creating empty list for result
num = 0
while num is lesser than len(items):
weight += items[num][2] #adding the weight first
if weight is lesser than maxweight:
for i in range n:
if len(result[n]) is not num + 1:
append the item ID into result
num += 1
else:
weight -= items[num][2]
num += 1
return result
我认为这是行不通的,因为指数会超出范围,我不确定这是否是这个问题的正确/最佳答案。任何需要改进的反馈或提示都将不胜感激 一般来说,这是一个组合问题,看起来比背包问题更复杂。 如果项目和人员数量较少,您可以尝试使用bruteforce(看起来像python的伪代码)
这意味着第0个项目分配给第1个人,第1个项目分配给第0个人等。您请求的表示不同,但应该不难转换。范围/公平性的衡量标准是什么?最大偏差、平均偏差还是其他?或者你可以选择任何合理的吗?@AskoldIlvento max price$在所有n个人中以最公平的方式分配物品价格!虽然没有一个确切的衡量标准,但我认为有人会尽可能想要一个公平的分配!是的,我想这是一个关于背包的高级问题。我想在代码函数中尝试这个解决方案,你能帮我翻译一下吗?“最佳分配”是空列表吗?分配的正确含义是什么?@nah fam,我用一个有效的pythonic代码更新了帖子。
best_allocation = None
best_value = inf
for allocation in itertools.product(range(npeople), repeat=nitem):
if check_allocation_is_feasible(allocation):
value = count_allocation_metrics (allocation)
if value < best_value:
best_value = value
best_ allocation = allocation
import itertools
import numpy
npeople = 3
nitems = 5
numpy.random.seed(100)
capacities = numpy.random.randint(100, 200, npeople)
weights = numpy.random.randint(10, 100, nitems)
costs = numpy.random.randint(1, 10, nitems)
def check_allocation_is_admissible(allocation):
burdens = [0]*npeople
for item, preson in enumerate(allocation):
burdens[preson] += weights[item]
if burdens[preson] > capacities[preson]:
return False
return True
def count_allocation_metrics(allocation):
total_cost = [0]*npeople
for item, preson in enumerate(allocation):
total_cost[preson] += costs[item]
max_deviation = 0
for c1 in total_cost:
for c2 in total_cost:
max_deviation = max(max_deviation, c1 - c2)
return max_deviation
best_allocation = None
best_value = numpy.inf
for allocation in itertools.product(range(npeople), repeat=nitems):
#allocation has number of items dimension and each element denotes who carry corresponding item
if check_allocation_is_admissible(allocation):
value = count_allocation_metrics(allocation)
if value < best_value:
best_value = value
best_allocation = allocation
print(best_allocation)
(1, 0, 2, 1, 2)