'Can I use a Python Dictionary to create combinations of teams?

I am trying to create 2 equal teams based on a python dictionary of players and their rating.

My thought process was to add all the ratings, half of that would be roughly one side. Once I have the output of one side, the other side would be the players remaining in the dictionary.

Is there a way to loop through combinations of 7 player teams and see if they are close to the one_team score?

dict_with_ints = {'Player 1': 5.25, 
'Player 2': 9.5, 
'Player 3': 3.25, 
'Player 4': 8.25, 
'Player 5': 5.75, 
'Player 6': 8.0, 
'Player 7': 9.25, 
'Player 8': 6.75, 
'Player 9': 7.0, 
'Player 10': 5.0, 
'Player 11': 1.75, 
'Player 12': 10.0, 
'Player 13': 4.5, 
'Player 14': 5.5}


total_score = sum(dict_with_ints.values())

one_team = sum(dict_with_ints.values())/2
​
print(total_score)
89.75

print(one_team)
44.875

print(len(dict_with_ints))
14


Solution 1:[1]

Using itertools.combinations will give you all combinations of 7 players you can have, and them you can look for one combination which minimize the distance between its score and the one_team score.

In details :


from itertools import combinations
import numpy as np

dict_with_ints = {'Player 1': 5.25, 
'Player 2': 9.5, 
'Player 3': 3.25, 
'Player 4': 8.25, 
'Player 5': 5.75, 
'Player 6': 8.0, 
'Player 7': 9.25, 
'Player 8': 6.75, 
'Player 9': 7.0, 
'Player 10': 5.0, 
'Player 11': 1.75, 
'Player 12': 10.0, 
'Player 13': 4.5, 
'Player 14': 5.5}

one_team = sum(dict_with_ints.values()) / 2
half_len = int(len(dict_with_ints) / 2)

list_of_first_teams = list(combinations(dict_with_ints, half_len))
len_combinations = len(list_of_first_teams)

score = np.empty(len_combinations)

for n, first_team in enumerate(list_of_first_teams):
    score[n] = sum(dict_with_ints[i] for i in first_team)

selected_team = np.argmin(np.abs(score - one_team))

selected_first_team = list_of_first_teams[selected_team]
selected_first_team
Out[48]: 
('Player 1',
 'Player 2',
 'Player 3',
 'Player 4',
 'Player 6',
 'Player 7',
 'Player 14')

selected_second_team = [i for i in dict_with_ints if i not in selected_first_team]
selected_second_team
Out[49]: 
['Player 5',
 'Player 8',
 'Player 9',
 'Player 10',
 'Player 11',
 'Player 12',
 'Player 13']

Of course, you can find a better way to implement that, maybe using combinations generator instead of constructing a list from it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zelemist