Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print this pattern? I cannot get the logic for eliminating the middle part

Write a program that asks the user for an input n (assume that the user enters a positive integer) and prints only the boundaries of the triangle using asterisks '*' of height n.

For example if the user enters 6 then the height of the triangle should be 6 as shown below and there should be no spaces between the asterisks on the top line:

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

I cannot understand how to print the part between top and end of pattern? This is my code:

n = int(input("Enter a positive integer value: "))
for i in range (n, 0, -1):
    print ("*" * i)

The for loop is for printing the reverse asterisks triangle. Obstacle is to print the middle part.

like image 351
Karan Thakkar Avatar asked Feb 22 '16 06:02

Karan Thakkar


2 Answers

In every iteration of the for loop You print one line of the pattern and it's length is i. So, in the first and the last line of the pattern You will have "*" * i. In every other line of the pattern you have to print one * at start of the line, one * at the end, and (i - 2) spaces in the middle because 2 stars were already printed out, which results in "*" + (" " * (i - 2)) + "*". After combining that two cases, we get the following code:

n = int(input("Enter a positive integer value: "))
for i in range(n, 0, -1):
    if i == 1 or i == n:   
        print("*" * i)
    else:
        print("*" + (" " * (i - 2)) + "*")
like image 83
Tony Babarino Avatar answered Oct 20 '22 06:10

Tony Babarino


Try the following, it avoids using an if statement within the for loop:

n = int(input("Enter a positive integer value: "))
print('*' * n)

for i in range (n-3, -1, -1):
    print ("*{}*".format(' ' * i))

print('*')

For 6, you will get the following output:

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

You could also handle the special case of 1 as follows:

n = int(input("Enter a positive integer value: "))

if n == 1:
    print '*'
else:
    print('*' * n)

    for i in range (n-3, -1, -1):
        print ("*{}*".format(' ' * i))

    print('*')
like image 44
Martin Evans Avatar answered Oct 20 '22 07:10

Martin Evans