Hollow Inverted Half Pyramid

Question:

I have to print a hollow inverted pyramid:

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

Following is my code:

n = int(input())

for i in range(n,0,-1):
    if i == n:
        print(n*'*', end = '')
    if  i > 1 and i <n:
        print('*'+(i-2)*' '+'*')
    else:
        print('*')
    print()

For input as 6 I am not sure why my code is printing 7 stars.
If anyone could help explain what I am doing wrong or missing would be really great!

Asked By: Avinash Jha

||

Answers:

There are two problems here:

  1. There is no need for the , end=''. You still want a newline to print after this line of stars.
  2. You used if not elif for the second condition, so the third block of code in the else will still run even if the first condition is true.

Here is the corrected code:

n = int(input())

for i in range(n, 0, -1):
    if i == n:
        print(n * "*")
    elif 1 < i < n:
        print("*" + (i - 2) * ' ' + '*')
    else:
        print('*')
Answered By: Lecdi

If the first iteration of the loop, there are two print calls executing: the first one and the last, so that makes a total of 7 stars in that first line of output.

As the first and last case are different from the other cases, it is easier to just deal with those outside of the loop:

n = int(input())

print(n*'*')
for i in range(n - 3, -1, -1):
    print('*' + i*' ' + '*')
if n > 1:
    print('*')

There is still one if here to ensure it still works correctly for n equal to 1 or even 0.

To do it without that if, you could do this:

n = int(input())

print(n*'*')
s = '*' + n*' '
for i in range(n - 2, -1, -1):
    print(s[:i] + '*')
Answered By: trincot

another type of inverted hollow matrix:
54321
4 1
3 1
2 1
1

Answers:

Hollow Right-angled triangle!!!

n=int(input())
for i in range(n,0,-1):
    for k in range(n,0,-1):
      if i==n or i==k or k==n-(n-1):
        print(k,end=" ")
    else:
        print(end="  ")
print()
Answered By: Kaushik G
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.