Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

In python 3.5, I just want to print the following pattern

    *

   ***

  *****

 *******

*********

 *******

  *****

   ***

    *

But the problem is, I just know how to print the following pattern, I don't know how to make it as diamond

n = 5

print("Pattern 1")

for a1 in range (0,n):

    for a2 in range (a1):

        print("*", end="")

    print()

for a1 in range (n,0,-1):

    for a2 in range (a1):

        print("*", end="")

    print()

*

**

***

****

*****

****

***

**

*

Anyone, please help me?

1 Answer

0 votes
by (26.4k points)

When you look the diamond pattern, The middle and largest row has 9 starts, so you have to make n equal to 9. So, In each row we have to create number of spaces and stars.

Row1: 4 spaces, 1 star, 4 spaces

Row2: 3 spaces, 3 stars, 3 spaces

Row3: 2 spaces, 5 stars, 2 spaces

Row4: 1 space, 7 stars, 1 space

Row5: 0 spaces, 9 stars, 0 spaces

Row6: 1 space, 7 stars, 1 space

Row7: 2 spaces, 5 stars, 2 spaces

Row8: 3 spaces, 3 stars, 3 spaces

Row9: 4 spaces, 1 star, 4 spaces

From the above description,  You can understand that, for row 1 to (n+1)/2, the number of stars increases as the number of space decreases. From 1 to 5, The number of stars=(row number*2)-1 and number of spaces before stars=5-row number.

Now, For row(n+1)/2 +1 to 9th row, The number of stars decreases as the number of spaces increases. So, From row number 6 to n, the number of  stars=((n+1- row number)*2)-1 and number number of spaces before stars= row number -5

Look at the following code, The program look like this:

n = 9

print("Pattern 1")

for a1 in range(1, (n+1)//2 + 1): #from row 1 to 5

    for a2 in range((n+1)//2 - a1):

        print(" ", end = "")

    for a3 in range((a1*2)-1):

        print("*", end = "")

    print()

for a1 in range((n+1)//2 + 1, n + 1): #from row 6 to 9

    for a2 in range(a1 - (n+1)//2):

        print(" ", end = "")

    for a3 in range((n+1 - a1)*2 - 1):

        print("*", end = "")

    print()

Want to learn more about Python? Come and Join:- Python course

Related questions

0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Dec 30, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 9, 2019 in Python by ParasSharma1 (19k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...