5

I would like to print the following pattern in Python 3.5 (I'm new to coding):

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

But I only know how to print the following using the code below, but not sure how to invert it to make it a complete 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()

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

Any help would be appreciated!

4
  • Consider that every line you print is a combination of spaces and asterisks (in your example, first line is 4 spaces, 1 asterisk, second line is 3 spaces, 3 astersisks, etc). All you have to do is to find out how many spaces and asterisks should be there on each line. Commented Sep 17, 2016 at 14:52
  • How can I print the spaces?
    – Ali R.
    Commented Sep 17, 2016 at 15:05
  • 2
    The exact same way you print asterisks. Commented Sep 17, 2016 at 15:07
  • Never mind! I was using ("") instead of (" ")! I'll try to do it now and update you if it works out!
    – Ali R.
    Commented Sep 17, 2016 at 15:09

19 Answers 19

12

Since the middle and largest row of stars has 9 stars, you should make n equal to 9. You were able to print out half of the diamond, but now you have to try to make a function that prints a specific number of spaces, then a specific number of stars. So try to develop a pattern with the number of spaces and stars in each row,

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

So what can you deduce? From row 1 to (n+1)/2, the number of spaces decreases as the number of stars increase. So from 1 to 5, the # of stars = (row number * 2) - 1, while # of spaces before stars = 5 - row number.

Now from row (n+1)/2 + 1 to row 9, the number of spaces increase while the number of stars decrease. So from 6 to n, the # of stars = ((n+1 - row number) * 2) - 1, while # of spaces before stars = row number - 5.

From this information, you should be able to make a program that looks 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()

Note that you can replace n with any odd number to create a perfect diamond of that many lines.

2
  • Another way to look at it is this way (below), but it is similar to the half diamond where n is for row 1 to the maximum asterisks, and not to the total number of rows. This way it eliminates the odd shape when using even numbers. I looked at the way you explained it and tried to come up with another method instead of having division, and following a strategy similar to the half diamond. for b1 in range (n): for b2 in range (n-b1): print(" ", end="") for b3 in range ((b1*2)-1): print("*", end="") print()
    – Ali R.
    Commented Sep 17, 2016 at 15:47
  • Of course, your repeat again for for b1 in range(n,0,-1)
    – Ali R.
    Commented Sep 17, 2016 at 15:52
8

Here is a solution base on height equals to top to the middle, or half of the height. For example, height is entered as 4(7) or 5(9) below. This method will yield odd number actual height

h = int(input("please enter diamond's height:"))

for i in range(h):
    print(" "*(h-i), "*"*(i*2+1))
for i in range(h-2, -1, -1):
    print(" "*(h-i), "*"*(i*2+1))

# please enter diamond's height:4
#      *
#     ***
#    *****
#   *******
#    *****
#     ***
#      *
#
# 3, 2, 1, 0, 1, 2, 3  space
# 1, 3, 5, 7, 5, 3, 1  star

# please enter diamond's height:5
#       *
#      ***
#     *****
#    *******
#   *********
#    *******
#     *****
#      ***
#       *
#
# 4, 3, 2, 1, 0, 1, 2, 3, 4  space
# 1, 3, 5, 7, 9, 7, 5, 3, 1  star

Here is another solution base on height equals to top to the bottom, or the actual total height. For example, height is entered as 7 or 9 below. When the user enters an even number for height, the diamond will be slightly slanted.

h = int(input("please enter diamond's height:"))

for i in range(1, h, 2):
    print(" "*(h//2-i//2), "*"*i)
for i in range(h, 0, -2):
    print(" "*(h//2-i//2), "*"*i)

# please enter diamond's height:7
#      *
#     ***
#    *****
#   *******
#    *****
#     ***
#      *
#
# 3, 2, 1, 0, 1, 2, 3  space
# 1, 3, 5, 7, 5, 3, 1  star
#
# please enter diamond's height:9
#       *
#      ***
#     *****
#    *******
#   *********
#    *******
#     *****
#      ***
#       *
#
# 4, 3, 2, 1, 0, 1, 2, 3, 4  space
# 1, 3, 5, 7, 9, 7, 5, 3, 1  star
2
  • 4
    There is no need to use eval, use int instead.
    – sanyassh
    Commented Feb 28, 2019 at 15:41
  • @sanyassh because eval is a security risk, I edited the code instead in accordance with your suggestion. Commented Nov 14, 2021 at 10:55
7

I learned a very simple solution today and would like to share it. :)

num = 9

for i in range(1, num+1):
  i = i - (num//2 +1)
  if i < 0:
    i = -i
  print(" " * i + "*" * (num - i*2) + " "*i)

The logic is the following:
(A space is represented as "0" here.)

# i = 1 | new i = 1 - 5 = -4 | * : 9 - 8 = 1 | 0000 + * + 0000
# i = 2 | new i = 2 - 5 = -3 | * : 9 - 6 = 3 | 000 + *** + 000
# i = 3 | new i = 3 - 5 = -2 | * : 9 - 4 = 5 | 00 + ***** + 00
# i = 4 | new i = 4 - 5 = -1 | * : 9 - 2 = 7 | 0 + ******* + 0
# i = 5 | new i = 5 - 5 = 0  | * : 9 - 0 = 9 |    ********* 
# i = 6 | new i = 6 - 5 = 1  | * : 9 - 2 = 7 | 0 + ******* + 0
# i = 7 | new i = 7 - 5 = 2  | * : 9 - 4 = 5 | 00 + ***** + 00
# i = 8 | new i = 8 - 5 = 3  | * : 9 - 6 = 3 | 000 + *** + 000
# i = 9 | new i = 9 - 5 = 4  | * : 9 - 8 = 1 | 0000 + * + 0000

The result would be the following:

    *    
   ***   
  *****  
 ******* 
*********
 ******* 
  *****  
   ***   
    *    
5

As pointed out by Martin Evans in his post: https://stackoverflow.com/a/32613884/4779556 a possible solution to the diamond pattern could be:

side = int(input("Please input side length of diamond: "))

for x in list(range(side)) + list(reversed(range(side-1))):
    print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
2
  • As I said I'm new to Python, I haven't learned that method yet and only know some commands.
    – Ali R.
    Commented Sep 17, 2016 at 15:41
  • 1
    @Ali R - this is a beginner's solution and it's easier than the one above. The curly brackets in the print statement look complicated, but they're actually simple once you learn them. Commented Sep 7, 2018 at 9:36
1

Simplest Answer

n=5
for i in range(1,n+1):
    print ((n-i)*(" ")+(i*" *"))

for i in range(n-1,0,-1):
    print((n-i)*(" ")+(i*" *"))

Hope this helps some one

1

Another possibility. Depending on which (space or star) one uses, (I used space) convert it to absolute value. This implementation doesn't require splitting the diamond into two loops (upper and lower halves).

def diamond(n):
    star = 1
    main = ''
    # if required to manage zero or negative n
    if n%2 == 0:
        return None
    if n<0:
        return None
    else:
        for i in range(1,n+1):
            string = ''
            space = abs(i - int((n+1)/2))
            star = n - 2 * space
            string = space * ' ' + star * '*' + '\n'
            main += string
        # not necessary but useful to visualize diamond 
        #print(main)
        return(main)
1

There are two version of this

  1. Space between Stars
  2. Without Space between Stars

Space between Stars

n = 4
for i in range(n):
    print(' '*(n-i-1) + '* '*(i+1) )
for i in range(n):
    print(' '*(i+1) + '* '*(n-i-1))

enter image description here

Without Space between Stars

n = 4
for i in range(n):
    print(' '*(n-i-1) + '*'*((2*i)+1) )
for i in range(n):
    print(' '*(i+1) + '*'*((2*((n-1)-i))-1))

enter image description here

0
side = int(input("side length: "))
count = 0
bl = 0
while count < side:
    x = side - count
    print (x * " ", (count * "*") * 2)
    count += 2
while count >= 0:
    print (bl * " ", (count * "*") * 2)
    count -= 1
    bl += 1

if you want both upper part and down side to be same change the count += 2 to count += 1

0
#author Tahir Baku
#have fun
print "\nWelcome to diamond builder"
print "\n----D.I.A.M.O.N.D  B.U.I.L.D----"
diagonal=int(input("Give me the diagonal: "))
s=1
h1=1
h=(diagonal-1)/2
diagonal1=diagonal-2
while s<=diagonal:
     print (' '*h+'*'*s+' '*h)
     h=h-1
     s=s+2
while diagonal1>=0:
     print (' '*h1+'*'*diagonal1+' '*h1)
     h1=h1+1
     diagonal1=diagonal1-2
1
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Commented Jul 25, 2018 at 15:43
0
print('This is in python 3.7')
h=eval(input('Enter the diagonal?'))
j=1
for i in range(h,h//2,-1):
    print(' '*(i-(h//2)-1),'*'*j)
    j+=2
j-=4
for i in range(1,(h//2)+1,1):
    print(' '*i,'*'*(j))
    j-=2
0

simple way ...

n= 11 #input is even number 1,3,5,...
a = 1
b = 1
for a in range(n+1):
    if a%2 != 0:
        val = (n - a) // 2
        print (" "*val + "*"*(a) + " "*val ,end = "\n")
for b in range(n-1,0,-1):
    if b%2 != 0:
        val2 = (n-b)//2
        print (" "*val2 + "*"*(b) + " "*val2 ,end = "\n")

Output:

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

Or using reverse method, first one is diamond, second one is series of diamond

import copy
n = 10       #input: size of diamon
raw  = []
lst = []
re_lst = []

for a in range(n+1):
    if a%2 != 0:
        val = (n - a) // 2
        raw = ''.join(" "*val + "*"*(a) + " "*val)
        lst.append(raw)
        re_lst = copy.deepcopy(lst)
lst.reverse()
#print diamond
for i in re_lst:
    print(i)
for i in lst:
    print(i)
print("\n")
#print series of diamond
for i in re_lst:
    print(i)
    for i in lst:
        print(i)
0
a = 10
for x in range (a):
  print(" " * (a - x) + "*" * (x+1) + "*" *(x))
#+ this = diamond
for x in reversed(range(a-1)):
    print(" " * (a - x) + "*" * (x) + "*" *(x+1))
0
def pattern2(row):
    s=1
    c = row / 2
    d = int(c)-1
    for i in range(1,row+1):
        if i<c:
            print(" "*d,star(s))
            s+=2
            d-=1
        elif i==(c+0.5):
            print(star(row))
            s=s-2
            d=0
        else:
            print(" "*d,star(s))
            s=s-2
            d+=1
def star(s):
    return '*'*s
def main():
    row=int(input("enter the no. of row but the rows should be odd \n#special case of pattern"))
    try:
        a=row%2
        assert a!=0 and row!=0
        pattern2(row)
    except:
        print('Worng selection of rows for the perfect diamond.')
if __name__=="__main__":
    main()
0
0
#maybe it could help  

height = eval ( input ( 'How high? ' ) )
height = int (height//2)

for i in range(1, height+1):
    print(' ' *(height-i+1), '*'*i + '*' * (i-1) )

for i in range (height+1, 0, -1):
    print (' ' * (height+1-i), '*' * i + '*' * (i-1))  
0

First find logic from the dressing table, then I think it's easier above all (n=11, m=(n+1)/2 = 6) : i    .   *
1   5   1
2   4   3
3   3   5
4   2   7
5   1   9
6   0   11
7   1   9
8   2   7
9   3   5
10  4   3
11  5   1 enter image description here

n = int(input("Input odd number of layers: "))
m = (n+1)/2
i = 1
while i<=n :
    if(i < m):
        b = m-i
        s = 2*i -1
    else:
        b = i-m
        s = 2*(n-i)+1
    j = 1 
    while j <= b:
        print('.',end="")    # dot or space 
        j += 1
    j = 1    
    while j <= s:
        print('*',end="")
        j+=1
    print()
    i += 1
0
h = int(input('Height -> '))

for i in range(h):
    if i <= (h // 2):
        print(' ' * (h // 2 - i), end='')
        print('*' * (i + 1), end='')
        print('*' * (i + 1))
    else:
        print(' ' * abs((h // 2 - i)), end='')
        print('*' * (h - i), end='')
        print('*' * (h - i))
0
length = 5
for i in range(1,length,2):
    space = length//2 -i//2
    print(" "*space, end="")
    print('*'*i)
for j in range(length, 0, -2):
    space = length//2 - j//2
    print(" "*space, end="")
    print('*'*j)
0

Here is a simple code using f-string formatting language

num = 9
num = num if num % 2 == 1 else 2 * num + 1
for i in range(1, num, 2):
    print(f"{i * '*': ^{num}}")
for i in range(num, 0, -2):
    print(f"{i * '*': ^{num}}")
    *    
   ***   
  *****  
 ******* 
*********
 ******* 
  *****  
   ***   
    *    
-1
#coder_rishabh_darmwal
#it_is_a_simple_codewith_an_easy_logic
row=int(input('enter the no. of rows')
for i in range(row):
    if i<=row//2:
        for j in range(row//2-i):
            print(" ",end='')
        for k in range(i*2-1):
        print("*",end="")
    print()
else:
    for j in range(i-row//2):
        print(" ",end="")
    for k in range((row-i)*2-1):
        print("*",end="")
    print()
#the output will be
[output for row=30][1]


#i also wrote a programme fro hollow diamonds
row=int(input('enter the no. of rows')
for i in range(row):
    if i<=row//2:
        for j in range(row//2-i):
            print(" ",end='')
        for k in range(i*2-1):
            if k==0 or k==i*2-2:
                print("*",end="")
            else:
                print(' ',end='')
        print()
    else:
        for j in range(i-row//2):
            print(" ",end="")
        for k in range((row-i)*2-1):
            if k==0 or k==(row-i)*2-2:
                print("*",end="")
            else:
                print(' ',end="")
        print()
[out for hollow rhombus row=20
][2]


  [1]: https://i.sstatic.net/3j0bx.png
  [2]: https://i.sstatic.net/tCxI3.png

Not the answer you're looking for? Browse other questions tagged or ask your own question.