Reputation: 93
i have list of names that i want to match for a tennis competition. The games are taking place once a week and everyone should have a new opponent each week till all pairings have been made.
To create 2 people combinations with all the players I did the following:
from itertools import combinations
names = [‘ben’,
‘josh’,
‘jessy’,
‘natalia’]
result = [[a + ‘-‘ + b] for a, b in combinations(names, 2)]
This gives the following:
[['ben - josh'],
['ben - jessy'],
[‘ben - natalia'],
['josh - jessy'],
['josh - natalia'],
['jessy - natalia']]
The last part is to match each player with someone who they’ve never played before. In order to do this i did the following:
for i, j in zip(range(int(len(result)/2)), (reversed(range(int(len(result) /2),len(result))))):
print(result[i], result[j]
This way each player plays with someone new each time. The result is:
['ben - josh'] ['jessy - natalia']
['ben - jessy'] ['josh - natalia']
['ben - natalia'] ['josh - jessy']
How I can extend the following to a much bigger list of players ? Lets say 100+ ? Is there any better way of doing this ? Also, what if the list of players has odd number of players ? Thanks for your help with this.
Upvotes: 0
Views: 34
Reputation: 27324
Even if your list contains 100+ names, the performance difference will be negligible.
An odd number of names is managed correctly using similar logic.
The second phase of your process can be simplified as follows:
from itertools import combinations
names = ["ben", "josh", "jessy", "natalia", "dan"]
pairs = list(combinations(names, 2))
m = len(pairs) // 2
for a, b in zip(pairs[:m], reversed(pairs)):
print(a, b)
('ben', 'josh') ('natalia', 'dan')
('ben', 'jessy') ('jessy', 'dan')
('ben', 'natalia') ('jessy', 'natalia')
('ben', 'dan') ('josh', 'dan')
('josh', 'jessy') ('josh', 'natalia')
Upvotes: 0