0

I want to make a pattern as shown below:

N = 1
*

N = 3
  *
***
  *

N = 5
    *
  ***
*****
  ***
    *

and so on...

Nevertheless, I write this program only works for N = 5. Could anybody please explain what the mistake is and what the solution is? Thanks.

N = int(input())
k = 1
for i in range(1, N - 1):
    for j in range(1, N + 1):
        if(j <= N - k):
            print(' ', end = '')
        else:
            print('*', end = '')
    k = k + 2
    print()

k = 2
for i in range(1, N - 2):
    for j in range(1, N + 1):
        if(j >= N - k):
            print('*', end = '')
        else:
            print(' ', end = '')
    k = k - 2
    print()

2 Answers 2

1

You are trying to print a pyramid of N lines with two for-loops using range. So the sum of of the lengths of your two ranges should be N.

Now consider the sum of for i in range(1, N - 1) and for i in range(1, N - 2) with some large N. Take N=99 for example:

len(range(1, 99 - 1)) + len(range(1, 99 - 2))
>>> 193

This is your first mistake. The function only works with N=5 because of the two minuses you have chosen for your ranges. What you need to do here is to rewrite your math:

len(range((99+1)//2)) + len(range((99-1)//2))
>>> 99

Note that I removed the starting value from ranges, as it is not needed here. By default, range starts to count from 0 and ends one number before the ending value.

The second mistake you have is with how you are printing the bottom half of the triangle. Basically, you have tried to reverse everything to print everything in reverse, but that has somehow broken the logic. What here we want to do is to print k empty spaces for each line, incrementing k by two for each line.

Function with minimal fixes:

N = int(input())
k = 1
for i in range((N+1)//2):
    for j in range(1, N + 1):
        if(j <= N - k):
            print(' ', end = '')
        else:
            print('*', end = '')
    k = k + 2
    print()

k = 2
for i in range((N-1)//2):
    for j in range(1, N + 1):
        if(j > k):
            print('*', end = '')
        else:
            print(' ', end = '')
    k = k + 2
    print()
Sign up to request clarification or add additional context in comments.

Comments

0

List comprehension is one pythonic trick to avoid multiple nested loops and can be very efficient. Another general guideline is to break down into smaller testable functions

N = 5

def print_pyramid(n):
    for i in [min(2*i+1, 2*n-2*i-1) for i in range(n)]:
        print((" " * (n-i)) + ("*" * i))

k = 1
while k <= N:
    print("N = " + str(k))
    print_pyramid(k)
    print("")
    k += 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.