[Python] Triangle of partition numbers in Python

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

  1. Stack

    Stack Membro Participativo

    I'm trying to make a dictionary corresponding to the triangle of partition numbers shown here:

    [​IMG]

    So I want to replicate the (underlined red) recurrence relation and end up with:

    {0: [1],
    1: [1, 1],
    2: [1, 1, 1],
    3: [1, 2, 1, 1],
    4: [1, 2, 2, 1, 1],
    5: [1, 3, 3, 2, 1, 1]}


    (I tried and failed to get the keys to equal n.) Here is my code:

    dic1 = {}
    for n in range(0,6):
    dic1[n] = [1]
    for i in range(0, 6):
    if n > 0 and i > 0:
    if i > n:
    continue
    elif n - i < i:
    dic1[n].append(dic1[n-1][i-1])
    else:
    dic1[n].append(dic1[n-1][i-1] + dic1[n-i])
    print(dic1)


    Which gives:

    {0: [1],
    1: [1, 1],
    2: [1, 2, 1],
    3: [1, 3, 2, 1],
    4: [1, 4, 4, 2, 1],
    5: [1, 5, 6, 4, 2, 1]}


    I just cannot see where I'm going wrong. Thank you.

    Continue reading...

Compartilhe esta Página