[Python] Generating all length-N combinations of all length-M sublists of a list, without...

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a long input list, and I want to generate combinations of 3 elements. But each combination's elements should be drawn from a length-5 sublist of the original list, rather than drawing elements from the whole list.

    Equivalently, no two elements of a combination can be spaced more than 4 positions apart in the original list.

    I wrote this code:

    import itertools

    input = [
    'a','b','c','d','e','f','g','h','i','j'
    ]
    l=0
    space = ' '
    count = 3
    run = 5

    def combine_list(input_list, count, run):
    list_out = []
    j=0
    k = (len(input)-run)+1
    while j < k:
    comb_set = input_list[j:run+j:]
    comb = itertools.combinations(comb_set,count)
    for i in comb:
    out = space.join(list(i))
    list_out += [out]
    j += 1
    return list_out

    x = combine_list(input,count, run)

    print(x, len(x))


    with this output:

    ['a b c', 'a b d', 'a b e', 'a c d', 'a c e', 'a d e', 'b c d', 'b c e', 'b d e', 'c d e', 'b c d', 'b c e', 'b c f', 'b d e', 'b d f', 'b e f', 'c d e', 'c d f', 'c e f', 'd e f', 'c d e', 'c d f', 'c d g', 'c e f', 'c e g', 'c f g', 'd e f', 'd e g', 'd f g', 'e f g', 'd e f', 'd e g', 'd e h', 'd f g', 'd f h', 'd g h', 'e f g', 'e f h', 'e g h', 'f g h', 'e f g', 'e f h', 'e f i', 'e g h', 'e g i', 'e h i', 'f g h', 'f g i', 'f h i', 'g h i', 'f g h', 'f g i', 'f g j', 'f h i', 'f h j', 'f i j', 'g h i', 'g h j', 'g i j', 'h i j'] 60


    But this produces duplicates. I can sort to remove them, but I would rather not make them in the first place.

    Continue reading...

Compartilhe esta Página