这是一种蛮力方法,我在 115 名玩家中选择了 5 名玩家(在我的笔记本电脑上为 1 分 42 秒)尝试过。将选择增加至仅 100 名玩家中的 20 名将需要超过 100,000 年的时间来执行。即使是 50 个中的 20 个也需要 4 天。
from itertools import combinations
# Set the following parameters as desired
nplayers = 5
price = 32
players = {
'Romeu': [4.5, 57.0],
'Neves': [5.5, 96.0],
'Townsend': [6.0, 141.0],
'Lucas Moura': [7.5, 105.0],
'Martial': [7.5, 114.0],
'David Silva': [7.5, 177.0],
'Fraser': [7.5, 180.0],
'Richarlison': [8.0, 138.0],
'Bernardo Silva': [8.0, 174.0],
'Sigurdsson': [8.0, 187.0],
}
if len(players) < nplayers:
raise IndexError("You selected {nplayers} players but there are only {len(players)} to choose from")
# Create a list of all combinations of players, store as triples (name, cost, score)
combos = combinations(((h, *t) for h, t in players.items()), nplayers)
top_score = 0
for c in combos:
if sum(p[1] for p in c) <= price:
score = sum(p[2] for p in c)
if score > top_score:
top_teams = [c]
continue
elif score == top_score:
top_teams.append(c)
if top_score:
print(top_teams)
else:
print(f"You can't afford a team for only {price}")
输出
[(('Romeu', 4.5, 57.0), ('Neves', 5.5, 96.0), ('Townsend', 6.0, 141.0), ('Fraser', 7.5, 180.0), ('Sigurdsson', 8.0, 187.0))]