pulp 示例2.A Set Partitioning Problem

高级硬件设计中的研究课题需要通过一系列约束(唯一起始时间约束、依赖约束和资源约束)来优化一个调度过程。所以就开始学习pulp。

pulp官方网站,pulp是python的一个库,可以用来解决线性规划问题。

首先复习一下优化模型的三要素:

  • 决策变量
  • 目标函数
  • 约束条件

A Set Partitioning Problem这个问题主要去解决这样一类问题——有时候需要将一个大集合(set)划分为小集合(subset),使每一个item只属于一个subset,但同时还需要满足一些其他的约束。
约束条件

  • subset的个数最多是5
  • subset的容量是4
  • item属于且仅属于一个subset

目标函数
每个subset中item的最大ASCII与最小ASCII的差值最小(对应的happy越大)

"""
A set partitioning model of a wedding seating problem

Authors: lympassion
"""

from pulp import *

max_tables = 5
max_table_size = 4
guests = 'A B C D E F G H I J K L M N O P Q R'.split()


def happiness(table):
    return abs(ord(table[0]) - ord(table[-1]))


possible_tables = [tuple(i) for i in allcombinations(guests, max_table_size)]

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


seat_model = LpProblem("seat model", LpMinimize)

# object function
seat_model += lpSum([happiness(i)*x[i] for i in possible_tables]) 


# constraint
seat_model += lpSum(x[i] for i in possible_tables) <= max_tables

for guest in guests:
    seat_model += lpSum(x[i] for i in possible_tables if guest in i) == 1


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


出错记录:

  • seat_model += lpSum([happiness(i)*x(i) for i in possible_tables])
    TypeError: ‘dict’ object is not callable
  • x = LpVariable.dict('table', possible_tables, lowBound=0, upBound=1, cat=LpInteger)这里由于调用LpVariable.dict()方法而出现了
    dict->TypeError: not all arguments converted during string formatting错误
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值