Horizontal Pyramid with vertical increase in values (Python)

Viewed 43

Looking to create a horizontal pyramid that takes height as an argument for the length of the base of the triangle, and incrementally increases the value in the vertical direction before moving to the next horizontal row.

I have tried the following code:

def triangle(height):
    
    count=0
    for i in range(height//2):
        count+=1
        for j in range(i+1):

            print(count+count*j,end=' ')
        print()

    for i in range((height-1)//2,-1,-1):
        count+=1
        for j in range(i+1):
            print(count+count*j,end=' ')
        print()

The above does not seem to be working to achieve the correct result for heights greater than 3:

examples of the shape I would like to print:

triangle(4)

    1
    2 5
    3 6
    4

triangle(5)

    1
    2 6
    3 7 9
    4 8
    5

Any help appreciated.

2 Answers

this works, may not be the pretiest solution.

Basically creating a list of each column, adding padding as long as i need at least 1 element in the list.

you add padding (0) for empty spaces . you then transpose and replace the 0 by an empty string.


def triangle(height):
    current_height= height
    matrix = []
    start = 1
    while N >= 1:
        row = []
        padding = int((height- current_height) / 2)

        for x in range(padding):
            row.append(0)
        for x in list(range(start, start+current_height)):
            row.append(x)
        for x in range(padding):
            row.append(0)

        start +=current_height
        current_height -=2
        matrix.append(row)
    print(matrix)

    # now let's transpose 
    matrix = [*zip(*matrix)]

    # now we print
    pretty_string = ""
    for row in matrix:
        for number in row:
            pretty_string += str(number) if number !=0 else ' '
        pretty_string += '\n'

    print (pretty_string)

I was able to complete the problem using the following code:

def triangle(height):
    
    count=0
    for i in range(height//2):
        count+=1
        for j in range(i+1):

            print(count+(height+1-count+i-j)*j,end=' ')
        print()

    for i in range((height-1)//2,-1,-1):
        count+=1
        for j in range(i+1):
            print(count+(count+i-j)*j,end=' ')
        print()
Related