[Python] generate all unique triplets

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

  1. Stack

    Stack Membro Participativo

    there is a series of triplets:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],[13, 14, 15]]


    (can be longer than that). They are all unique.

    Q: What is the efficient way of generating all possible combinations of these triplets such that none of the items that have met before, 'meet' again?

    So for instance in this sequence none of triplets contain any items that encountered before:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12],[13, 14, 15]]
    [[1, 5, 9], [4, 8, 12], [7, 11, 15], [10, 14, 3],[2, 6, 13]]
    [[1, 4, 7], [5, 8, 11], [9, 12, 15], [10, 13, 2],[14, 3, 6]]


    but this one would not work:

    [[1, 5, 9], [4, 6, 12], [7, 11, 15], [10, 14, 3],[2, 8, 13]]


    because 4 and 6 from the second triplet have been in the same triplet before, specifically in [4, 5, 6] of the first record

    I think that it can be done by picking random triplets from initial sequence using random.sample(l, 3) and then check if this triplet has not been used before, but it looks pretty unefficient and I wonder if there is a nicer way.

    UPDATE:::

    I realised that it makes sense to post a code that being ugly and inefficient still works, just to illustrate what I am talking about:

    import random
    import itertools

    z = list(range(1, 10))
    group_size = 3
    superset = list()



    def check_not_met(x):
    for i in superset:
    if set(x).issubset(set(i)):
    return False
    return True


    def check_not_anyone_met(x):
    for i in itertools.combinations(x, 2):
    if not check_not_met(i):
    return False
    return True


    subsession_matrices = list()


    def generating_subsession(seq):
    subglobal = list()
    while seq:
    x = a[-group_size:]
    if check_not_anyone_met(x):
    subglobal.append(x)
    else:
    return False
    del seq[-group_size:]
    return subglobal

    for j in range(10000):
    a = z.copy()
    random.shuffle(a)
    subsession_matrix = generating_subsession(a)
    if not subsession_matrix:
    continue
    else:
    subsession_matrices.append(subsession_matrix)
    superset.extend(subsession_matrix)

    print(subsession_matrices)


    and the output is:

    [[3, 7, 1], [8, 2, 4], [6, 5, 9]]
    [[8, 1, 9], [3, 5, 2], [7, 6, 4]]
    [[3, 8, 6], [1, 4, 5], [7, 2, 9]]
    [[8, 5, 7], [1, 2, 6], [3, 9, 4]]

    Continue reading...

Compartilhe esta Página