Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a list in a triangular shape in python?

Tags:

python

I have a code that generates a list of values to form a Romberg Triangle. The list is always a triangular length (3, 6, 10, 15). How do I print a list like this in triangular form?

What I currently have:

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

Print statement that I want:

1 
2 5 
3 6 8
4 7 9 10
like image 754
Adam Glaze Avatar asked Oct 25 '25 02:10

Adam Glaze


1 Answers

Try this:

def getLength(n):
    i = 1
    s = 1
    while ( s < n ):
        i += 1
        s = s + i
    return i

def printTriangle(a):
    l = len(a)
    lt = getLength(l)
    for i in range(lt):
        d = lt - 2
        s = 0
        for j in range(i+1):
            print(a[i+j+s], end=' ')
            s += d
            d -= 1
        print('')

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

printTriangle(a)

The getLength function just calculates the height of the triangle and the printTriangle function handles the actual printing logic.

like image 68
MD.Tabish Mahfuz Avatar answered Oct 26 '25 17:10

MD.Tabish Mahfuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!