当前位置:网站首页>用pulp库解决运输问题【详细】
用pulp库解决运输问题【详细】
2022-08-03 05:11:00 【北北的巷栀酒】
这是一个非常经典的运输问题:

我发现网上有许多关于这个问题的代码,但是都没有注释或解说,所以我在代码中加上了注释,以便于更好的理解,有不懂的欢迎留言,或者看看我的另一篇文章https://blog.csdn.net/m0_59309242/article/details/119352731,或许就能找到答案
import pulp
import numpy as np
from pprint import pprint #导入库函数
def transportation_problem(costs, x_max, y_max):
row = len(costs) #规定行数
col = len(costs[0]) #规定列数
prob = pulp.LpProblem(sense=pulp.LpMaximize)
var = [[pulp.LpVariable(f'x{i}{j}', lowBound=0, cat='Integer') for j in range(col)] for i in range(row)] #规定变量,此处的f''是为了将x,y传给i,j
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x] #匿名函数,总而言之是为了变成一维数组
prob += pulp.lpDot(flatten(var), costs.flatten()) #做点积
for i in range(row):
prob += (pulp.lpSum(var[i]) <= x_max[i]) #lp计算序列的和,用lpsum比普通的sum快很多;此处属于添加条件使各作物小于计划播种面积
for j in range(col):
prob += (pulp.lpSum([var[i][j] for i in range(row)]) <= y_max[j])
prob.solve()
return {'objective':pulp.value(prob.objective), 'var': [[pulp.value(var[i][j]) for j in range(col)] for i in range(row)]}
if __name__ == '__main__':
costs = np.array([[500, 550, 630, 1000, 800, 700],
[800, 700, 600, 950, 900, 930],
[1000, 960, 840, 650, 600, 700],
[1200, 1040, 980, 860, 880, 780]])
max_plant = [76, 88, 96, 40]
max_cultivation = [42, 56, 44, 39, 60, 59]
res = transportation_problem(costs, max_plant, max_cultivation) #调用函数
print(f'最大值为{res["objective"]}')
print('各变量的取值为:')
pprint(res['var'])代码中flatten的用法在这儿https://blog.csdn.net/m0_59309242/article/details/119464565
得到的结果是:

边栏推荐
- 快速上手 Mockito 单元测试框架
- Harmony OS Date ano UI 】 【 】 the basic operation
- Flask的简单介绍及使用方法简介
- VR全景展打造专属元宇宙观展空间
- MCM box model modeling method and source analysis of atmospheric O3
- flask 面试题 问题
- mysql 存储过程 动态参数 查询执行结果
- OptionError: ‘Pattern matched multiple keys‘
- 高效率科研神器——小软件、大能量
- Talking about GIS Data (6) - Projected Coordinate System
猜你喜欢

Power button 561. An array of split
高效率科研神器——小软件、大能量

【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability

集合框架知识

13.
lt.647. Palindromic substring + lt.516. Longest palindrome subsequence 
Modified BiotinDIAZO-Biotin-PEG3-DBCO|diazo-biotin-tripolyethylene glycol-diphenylcyclooctyne

Pr第二次培训笔记

typescript44-对象之间的类兼容器

传说中可“免费白拿”的无线路由器 - 斐讯 K2 最简单刷 breed 与第三方固件教程

Object类与常用API
随机推荐
Talking about GIS Data (6) - Projected Coordinate System
1089 狼人杀-简单版 (20 分)
Tributyl-mercaptophosphane "tBuBrettPhos Pd(allyl)" OTf), 1798782-17-8
Js学习笔记(四)
传说中可“免费白拿”的无线路由器 - 斐讯 K2 最简单刷 breed 与第三方固件教程
【特征选取】计算数据点曲率
1054 求平均值 (20 分)
曲线特征----曲线弯曲程度的探究
网络流媒体下载的 10 种方法(以下载 Echo 音乐为例)
集合框架知识
CAD有生僻字如何打出来、如何提交软件相关问题或建议?
2.ROS通信机制
嵌入式-I2C-物理电路图
typescript49-交叉类型
在树莓派上搭建属于自己的网页(2)
Pr第四次培训笔记
1058 选择题 (20 分)(C语言)
13.
lt.647. Palindromic substring + lt.516. Longest palindrome subsequence 1060 爱丁顿数 (25 分)
13.< tag-动态规划和回文字串>lt.647. 回文子串 + lt.516.最长回文子序列