[Python] Combinations without using "itertools.combinations"

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    What I'd need is to create combinations for two elements a time.

    If a list contains: seq = ['A', 'B', 'C'] the output would be com = [['A', 'B'], ['A', 'C'], ['B', 'C']]

    all this without itertools.combinations method.

    I used the following code for the permutations. But how could I modify it to make it work with the combinations?

    def permute(seq):

    if len(seq) <= 1:
    perms = [seq]
    else:
    perms = []
    for i in range(len(seq)):
    sub = permute(seq[:i]+seq[i+1:])
    for p in sub:
    perms.append(seq[i:i+1]+p)

    return perms

    Continue reading...

Compartilhe esta Página