[Python] Creating a list of integer lists that have a fixed length and contain integers that...

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

  1. Stack

    Stack Membro Participativo

    I am trying to write some code that will generate all lists of a fixed length that have the property that the next integer in each list will either be same or an increment of the previous integer. All lists should start with 0.

    I can write code that does this for size 4 BUT it uses 3 nested loops. If I want to continue down this path I will have to have n - 1 nested loops.

    Just to be clear I will give some examples for length 5:

    [0, 0, 0, 0, 0]
    [0, 0, 1, 1, 1]
    [0, 1, 2, 2, 2]
    [0, 1, 2, 3 ,3]


    The code will return all such lists of length 5. Instead of down voting, could you help me improve my question?

    Here is my (really bad but working) code:

    import math

    def index_list(x):
    IL = []
    for i in [0,1]:
    for j in [0,1,2]:
    for k in [0,1,2,3]:
    if i <= j and j <= k and abs(i-j) < 2 and abs(j-k) < 2:
    IL.append([x, x + i, x + j, x + k])
    return IL

    print(index_list(0))


    this produces:

    [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 2], [0, 1, 1, 1], [0, 1, 1, 2], [0, 1, 2, 2], [0, 1, 2, 3]]


    I have included a argument x as i wish to have the code to sometimes do the same thing but with a different starting index.

    Continue reading...

Compartilhe esta Página