Home > Software engineering >  Creating hollow pyramid with solid top layer in python
Creating hollow pyramid with solid top layer in python

Time:04-01

I need to create a hollow pyramid with a solid top layer like so:

Height: 5

     *
    ***
   *   *
  *     *
 *********

Also needs a user input for height/number of rows, so it can't just be hardcoded, for example with a height of 4:

    *
   ***
  *   *
 *******

Using this code I received this output with no solid layer on top:

     *
    * *
   *   *
  *     *
 *********

n = 5
for i in range(n):
    for j in range(n - i - 1):
        print(' ', end='')

    for k in range(2 * i   1):
        if k == 0 or k == 2 * i:
            print('*', end='')
        else:
            if i == n - 1:
                print('*', end='')
            else:
                print(' ', end='')
    print()

CodePudding user response:

Here's a modified version of your code that prints the triangle correctly. Note the change to the if statements.

n = 5
for i in range(n):
    for j in range(n - i - 1):
        print(' ', end='')

    for k in range(2 * i   1):
        if k in [0,2*i]:
            print('*', end='')
        else:
            if i in[1,n - 1]:
                print('*', end='')
            else:
                print(' ', end='')
    print()

Alternatively, here's a "one line" solution.

n = 5
print('\n'.join([' '*(n-i-1) '*'*(2*i 1) 
    if i in [0,1,n-1] 
    else (' '*(n-i-1) '*' ' '*(2*i-1) '*') 
    for i in range(n)]))

CodePudding user response:

Add a condition which when the layer printing is 1, print '*'

Code:

def print_pyramid(total_layers):
    for current_layer in range(total_layers):
        
        for _ in range(total_layers - current_layer - 1):
            print(' ', end='')

        for column in range(2 * current_layer   1):
            # if left bound, right bound, or the layer is the first or last layer, print '*'
            if column == 0 or column == 2*current_layer or current_layer == 1 or current_layer == total_layers-1:
                print('*', end='')
            else:
                print(' ', end='')

        print()

print_pyramid(5)

Output:

    *
   ***
  *   *
 *     *
*********
  • Related