[Python] How to generate a given number of size N pairings from a list with minimum overlap...

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a list, lst

    lst = ['A','B','C','D','E','F','G']



    From this list, I want to generate a given number of lists, each of length N with the minimum possible amount of overlap between each item in lst.

    For example, let's say I want to generate three lists of length three from lst by hand, and I come up with the following:

    ['A','B','C']
    ['D','E','F']
    ['G','A','B']


    With the length of lst and my parameters - three lists of length three - I actually did this sub-optimally, as A and B are in the same output twice. I understand repeats are unavoidable, but they still can be handled optimally. The following output is an example of what I am trying to achieve, as the output consists of the minimum amount of pairings between each item in lst as possible:

    ['A','B','C']
    ['D','E','F']
    ['G','A','D']


    Of course, this is easy to do manually when parameters are really small, but as they get larger it becomes increasingly difficult - and time consuming - to optimize it manually.

    I have tried looking through itertools docs, but can't quite find something that could help me (probably not looking or thinking hard enough...) cycle() came to mind, but that just cycles through the items in a list and doesn't handle either the generation of sublists nor the handling of minimum possible overlap. I would still think cycle()is useful here as I want an evenly distributed amount of each item fromlst` in the output lists. Also, is there a name for this type of problem? Some sort of graph theory? Thanks in advance for any help!

    Continue reading...

Compartilhe esta Página