lingaaah
lingaaah

Reputation: 31

Creating hollow pyramid with solid top layer in python

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()

Upvotes: 0

Views: 331

Answers (2)

Ben Grossmann
Ben Grossmann

Reputation: 4772

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='')
        elif 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)]))

Upvotes: 1

Fed_Dragon
Fed_Dragon

Reputation: 1358

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:

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

Upvotes: 0

Related Questions