python 线性规划问题(pulp库的一个实例) 1.3

https://pythonhosted.org/PuLP/CaseStudies/a_set_partitioning_problem.html

这次是一个整数规划的问题,引入01决策变量,在线性规划中设置01变量即,把决策变量的上下限变为01,并设定为整数

x = pulp.LpVariable.dicts('table', possible_tables, lowBound = 0,upBound = 1,
                            cat = pulp.LpInteger)

以下欣赏代码,最关键的地方已经说明。
补充说明放在最后。

import pulp
max_tables = 5
max_table_size = 4
guests = 'A B C D E F H I J K M N O P Z W'.split()
def happiness(table):
    """
    Find the happiness of the table
    - by calculating the maximum distance between the letters
    """
    return abs(ord(table[0]) - ord(table[-1]))

# 列表化所有的方案
possible_tables = [tuple(c) for c in pulp.allcombinations(guests, 
                                        max_table_size)]

# 设置变量
x = pulp.LpVariable.dicts('table', possible_tables, 
                            lowBound = 0,
                            upBound = 1,
                            cat = pulp.LpInteger)

seating_model = pulp.LpProblem("Wedding Seating Model", pulp.LpMinimize)


# x对应一种方案,a对应效益,各个方案的效益总和即为目标函数
# 效益总和 a1x1 + a2x2 + a3x3 + a4x4
seating_model += sum([happiness(table) * x[table] for table in possible_tables])

#限定决策变量的总数目
# x1+x2+x3...<= 某个值
seating_model += sum([x[table] for table in possible_tables]) <= max_tables, \
                            "Maximum_number_of_tables"                  

# 每个客人只能出席一桌
# 这个语句需要留意一下
for guest in guests:
    seating_model += sum([x[table] for table in possible_tables
                                if guest in table]) == 1, "Must_seat_%s"%guest

seating_model.solve()

print("The choosen tables are out of a total of %s:"%len(possible_tables))
for table in possible_tables:
    if x[table].value() == 1.0:
        print(table)

最后补充一下
.split()方法留意一下,字符串列表化
.allcombinations()方法

possible_tables = [tuple(c) for c in pulp.allcombinations(guests, max_table_size)]

组元化所有分配方案,两个参数,一个是基本组成,另外一个是最大长度

尝试过5035个变量的决策,用时436s,还是比较可靠的

猜你喜欢

转载自blog.csdn.net/qq_42731466/article/details/82082767
1.3