[Python] Shuffle and match list elements so that no duplicate matches can be made

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    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, 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.

    Continue reading...

Compartilhe esta Página