本文为本人的学习笔记,若有错误请各位大佬纠正!
程序简介
以下是本程序的大致规划
输入:当前气温、不同服装提供的温度
输出:合适的穿衣搭配
具体内容
输入
气温
该程序需要用户输入目前的气温,具体代码如下:
temperature = int(input('目前气温:'))
cloth_temperature = 26 - temperature
服装提供的温度
我将服装名称与其提供的温度保存为一个Excel表格,表格内容如下所示:
T恤 | 1 |
衬衫 | 2 |
针织开衫 | 3 |
薄毛衫 | 3 |
卫衣 | 3 |
西装外套 | 4 |
厚毛衣 | 4 |
风衣 | 5 |
棉服 | 5 |
轻薄羽绒服 | 6 |
双面呢大衣 | 7 |
羽绒服 | 9 |
皮草 | 12 |
并使用pandas库读取表格,代码如下:
import pandas as pd
cloth = pd.read_excel('数据.xlsx', index_col=None, header=None)
cloth_list = [np.array(cloth)[i].flatten()[0] for i in range(0, len(np.array(cloth)))]
temperature_list = [np.array(cloth)[i].flatten()[1] for i in range(0, len(np.array(cloth)))]
建立数学规划模型
我们希望衣服提供的温度之和(程序中的cloth_temperature)加上当前的温度(程序中的temperature)尽可能与26℃接近,因此需要引入松弛变量(程序中的slack),则目标函数就为求松弛变量的最小值。
首先,定义所需要用到的变量。其中,slack为松弛变量,x为不同衣服提供的温度(根据之前的表格内容,此处应有x[0]~x[12]共13个变量),代码如下:
import cvxpy as cp
slack = cp.Variable(1)
x = cp.Variable(len(cloth_list), integer=True)
其次,将温度数据转化为1行x列(x为表格中的总行数)的矩阵
import numpy as np
T = np.array(temperature_list)
在进行规划求解之前,需要明确一下约束条件:
每种衣服最多穿1件;
至少穿一件T恤或衬衫,作为打底。
求解
明确约束条件之后,便可以规划求解,代码如下:
import cvxpy as cp
obj = cp.Minimize(cp.abs(slack))
cons = [
T @ x + slack == cloth_temperature,
x >= 0,
x <= 1, # 每种衣服最多穿1件
x[0] + x[1] >= 1 # 至少穿一件T恤或衬衫
]
prob = cp.Problem(obj, cons)
prob.solve()
输出
输出部分的代码如下:
cloth_final = []
a = 0
for cloth_number in x.value:
if cloth_number > 0:
cloth_final.append(f'{int(cloth_number + 0.5)}件' + cloth_list[a])
a += 1
print(f'今天气温为{temperature}℃,应该穿{cloth_final}。')
样例
若当前气温为12℃,则输出结果如下:
今天气温为12℃,应该穿['1件T恤', '1件针织开衫', '1件薄毛衫', '1件卫衣', '1件西装外套']。
若当前气温为26℃,则输出结果如下:
今天气温为26℃,应该穿['1件T恤']。
若当前气温为33℃,则输出结果如下:
今天气温为33℃,应该穿['1件T恤']。
完整代码
import numpy as np
import cvxpy as cp
import pandas as pd
temperature = int(input('目前气温:'))
cloth_temperature = 26 - temperature
cloth = pd.read_excel('数据.xlsx', index_col=None, header=None)
cloth_list = [np.array(cloth)[i].flatten()[0] for i in range(0, len(np.array(cloth)))]
temperature_list = [np.array(cloth)[i].flatten()[1] for i in range(0, len(np.array(cloth)))]
slack = cp.Variable(1)
x = cp.Variable(len(cloth_list), integer=True)
T = np.array(temperature_list)
obj = cp.Minimize(cp.abs(slack))
cons = [
T @ x + slack == cloth_temperature,
x >= 0,
x <= 1, # 每种衣服最多穿1件
x[0] + x[1] >= 1 # 至少穿一件T恤或衬衫
]
prob = cp.Problem(obj, cons)
prob.solve()
cloth_final = []
a = 0
for cloth_number in x.value:
if cloth_number > 0:
cloth_final.append(f'{int(cloth_number + 0.5)}件' + cloth_list[a])
a += 1
print(f'今天气温为{temperature}℃,应该穿{cloth_final}。')