我在this guide之后创建了一个脚本,以优化阵容,尽管该脚本大部分可用,但几乎总是返回U位置的重复值。我敢肯定那是因为结构创建的行看起来很独特,但并非如此。例如,我的最后一次回报是:
('C_jeff_carter','=',1.0) (“ U_jeff_carter”,“ =”,1.0)
显然是同一个人,但是python不知道,因为变量是相同的。我不太确定该如何拆分,以便LPsolve知道它们是不同的。
下面的代码sample data here。
import urllib, json
import pandas as pd
import re
from itertools import permutations
from pulp import *
import csv
current = pd.read_csv('new_proj.csv', parse_dates=True)
salaries = {}
points = {}
## Add U position
U = current[current.Position.isin(["W","C","D"])].copy()
U.Position = "U"
current = pd.concat([current, U])
for pos in current.Position.unique():
available_pos = current[current.Position == pos]
salary = list(available_pos[["Name","Salary"]].set_index("Name").to_dict().values())[0]
point = list(available_pos[["Name","Modeled_Prepalce"]].set_index("Name").to_dict().values())[0]
salaries[pos] = salary
points[pos] = point
## add a
pos_num_available = {"G": 1, "U": 1, "W": 3, "C": 2,"D": 2}
SALARY_CAP = 50000
_vars = {k: pulp.LpVariable.dict(k, v, cat="Binary") for k, v in points.items()}
prob = pulp.LpProblem("Fantasy", pulp.LpMaximize)
rewards = []
costs = []
position_constraints = []
# Setting up the reward
for k, v in _vars.items():
costs += pulp.lpSum([salaries[k][i] * _vars[k][i] for i in v])
rewards += pulp.lpSum([points[k][i] * _vars[k][i] for i in v])
prob += pulp.lpSum([_vars[k][i] for i in v]) <= pos_num_available[k]
prob += pulp.lpSum(rewards)
prob += pulp.lpSum(costs) <= SALARY_CAP
prob.solve()
def summary(prob):
div = '---------------------------------------\n'
print("Variables:\n")
score = str(prob.objective)
constraints = [str(const) for const in prob.constraints.values()]
for v in prob.variables():
score = score.replace(v.name, str(v.varValue))
constraints = [const.replace(v.name, str(v.varValue)) for const in constraints]
if v.varValue != 0:
print(v.name, "=", v.varValue)
print(div)
print("Constraints:")
for constraint in constraints:
constraint_pretty = " + ".join(re.findall("[0-9\.]*\*1.0", constraint))
if constraint_pretty != "":
print("{} = {}".format(constraint_pretty, eval(constraint_pretty)))
print(div)
print("Score:")
score_pretty = " + ".join(re.findall("[0-9\.]+\*1.0", score))
print("{} = {}".format(score_pretty, eval(score)))
summary(prob)