与Python di的组合求和

2024-06-07 21:40:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个幻想足球(足球)数据的dict,其中元组中的第一个值是价格,第二个值是本赛季的预期积分。其中的一部分如下所示:

 '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],

我想做的是写一个程序,允许我设置一个价格限制,并返回一个固定长度的组合,例如n=5,它有最大的分数。你知道吗

所以如果我把价格限制设置为32,我想要5名球员,它会返回罗密欧,内维斯,汤森,西格德森,弗雷泽。你知道吗

有人能给我一个正确方向的提示吗?我不知道该怎么开始。你知道吗


Tags: 数据价格silvadict幻想元组david足球
1条回答
网友
1楼 · 发布于 2024-06-07 21:40:54

这是一个暴力的方法,我已经尝试了选择5个球员115(1分42秒在我的笔记本电脑上)。从100名玩家中增加到20名玩家将需要10万年的时间来执行。即使是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))]

相关问题 更多 >

    热门问题