代码没错啊,不过要稍微改下,那个类都没用,没必要。
输出结果:
[Bash shell] 纯文本查看 复制代码 下料总数:3
No: 1 used:5900 [2300, 1200, 800, 800, 800]
No: 2 used:800 [800]
No: 3 used:800 [800]
代码:
[Python] 纯文本查看 复制代码
def GetBestPlan(dict_plan):
planLis = [y for y in dict_plan for x in range(0, dict_plan[y])]
planLis.sort(reverse=True)
res = [] # 计划表
n = -1 # 当前分割序号
while planLis :
res.append([])
n += 1
Longest = planLis[0] # 取当前最长的一根加入计划
res[n].append(Longest)
surplusBest = [] # 剩余长度的最优组合
surplusLong = 6000 - Longest # 6000是原材料长度
if surplusLong == 0: # 剩余长度surplusLong为0,跳到下一根计划
planLis.remove(Longest)
continue
# 过滤超过剩余长度的
rightPrepare = list(filter(lambda x: x <= surplusLong, planLis[1:]))
if not rightPrepare: # 无可以分割项,跳到下一根计划
planLis.remove(Longest)
continue
left,right = 0,1 # 剩余长度组合标记
currentComp = [] # 当前组合
while left < len(rightPrepare) - 1:
# 当前组合为空,添加左标记
if not currentComp : currentComp.append(rightPrepare[left])
t = surplusLong - sum(currentComp)
if t == 0 : # 最佳计划,退出循环
surplusBest = currentComp
break
t = surplusLong - sum(currentComp) - rightPrepare[right]
if t < 0 :
# 组合超出剩余长度
# 对比最佳计划,如果更佳则替换
# 左标记右移,又标记还原到到左标记+1
if sum(currentComp) > sum(surplusBest) : surplusBest = currentComp
left += 1
right = left + 1
currentComp = []
else:
currentComp.append(rightPrepare[right])
if right == len(rightPrepare) - 1 :
# 如果右标记已经到末尾,对比最佳计划,如果更佳则替换
# 左标记右移1,右标记还原到左标记+1
if sum(currentComp) > sum(surplusBest): surplusBest = currentComp
left += 1
right = left + 1
currentComp = []
else:
# 右标记右移1
right += 1
# 添加到计划,并删除已添加项
for x in surplusBest:
res[n].append(x)
planLis.remove(x)
planLis.remove(Longest)
return res
test = {1200: 1, 800: 5, 2300: 1}#要切割的长度及数量
res = GetBestPlan(test)
print("下料总数:%d" % len(res))
for inx, item in enumerate(res):
print("No:%2d used:%.0f" % (inx + 1, sum(item)), item)#输出切割方法 |