Trikstar Pandora
Trikstar Pandora

Reputation: 1

Printing a simple rhombus pattern in Python 3

I want to print this pattern in Python 3 (I'm a beginner):
Rhombus image

What i have tried :

n = 5

for x in range(1, (n+5) //2 + 1):
    for y in range( (n+5) //2 - x):
        print(" ", end = "")
    for z in range( (x*2)-1 ):
        print("*", end = "")
    print()

for x in range( (n+5)// 2 + 1, n + 5):
    for y in range(x - (n+5) //2):
        print(" ", end = "")
    for z in range( (n+5 - x) *2 - 1):
        print("*", end = "")
    print()

But the result is like this:
Rhombus

How can I make the middle hollow like in the image?

Thanks.

Upvotes: 0

Views: 7555

Answers (4)

melosidy
melosidy

Reputation: 1

How to make a "Hollow Diamond In Python 3.10" You can use this code here: my personal code

Upvotes: 0

Rohit
Rohit

Reputation: 1

Simple python code without using functions

rows = 7

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

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

Output:

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

Upvotes: 0

handle
handle

Reputation: 6369

With recursion:

def print_stars(i,n):
    if i:
        print( ' '*(n-i-1)  + '*' + ' '*(2*i-1) + '*')
    else:
        print( ' '*(n-1)  + '*')

# recursive
def r(n, i=0):
    print_stars(i,n) # up
    if i<n-1:
        r(n, i+1) # recurse
        print_stars(i,n) # down

# start
r(5)

prints:

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

Upvotes: 0

unutbu
unutbu

Reputation: 880987

The coordinates of the points on the hollow rhombus satisfies |x|+|y|==m (where m = n-1). Therefore, you could use

In [29]: m = n-1; print('\n'.join([''.join(['*' if abs(row)+abs(col)==m else ' ' for col in range(-m,m+1)]) for row in range(-m,m+1)]))
    *    
   * *   
  *   *  
 *     * 
*       *
 *     * 
  *   *  
   * *   
    *    

or, equivalently, but without list comprehensions:

n = 5
m = n-1
for row in range(-m, m+1):
    for col in range(-m, m+1):
        if abs(row) + abs(col) == m:
            c = '*'
        else:
            c = ' '
        print(c, end='')
    print()

To make the solid rhombus, simply change the condition to abs(row) + abs(col) <= m.

Upvotes: 3

Related Questions