Touseeq Ali Hassan
Touseeq Ali Hassan

Reputation: 43

print a diamond of numbers in python

      1
     121
    12321
   1234321
  123454321
   1234321
    12321
     121
      1

I can only print stars but have no logic for numbers.

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

if userInput > 0:
    for i in range(userInput):
        for s in range(userInput -3, -2, -1):
            print(" ", end="")
        for j in range(i * 2 -1):
            print("*", end="")
        print()
    for i in range(userInput, -1, -1):
        for j in range(i * 2 -1):
            print("*", end="")
        print()

Upvotes: 2

Views: 3451

Answers (3)

s3dev
s3dev

Reputation: 9711

Another (very simple) way to handle this is to take advantage of:

  1. The call stack.
  2. The mathematical property of elevens where: n = a^2.

For example:

  • 1 = 1^2
  • 121 = 11^2
  • 12321 = 111^2
  • 1234321 = 1111^2
  • etc ...

Example Function:

def diamond(n, c=1):
    """Print a diamond pattern of (n) lines.

    Args:
        n (int): Number of lines to print.

    """
    string = f'{int("1"*c)**2:^{n}}'
    if c < (n//2)+1:
        print(string)
        diamond(n=n, c=c+1)
    if c <= n:
        print(string)

>>> diamond(7)

Output:

   1   
  121  
 12321 
1234321
 12321 
  121  
   1   

Implementation Note:

There are different ideas as to whether n applies to the number of lines printed, or the center value of the diamond. This example implements the former; but is easily modified to implement the latter.

Upvotes: 0

user2390182
user2390182

Reputation: 73470

The following can do this concisely using a helper function:

def up_and_down(n):  # 1,2, ..., n, ..., 2, 1
    return (*range(1, n), *range(n, 0, -1))

def diamond(n):
    for i in up_and_down(n):
        print((n-i)*' ', *up_and_down(i), sep='') 
       
>>> diamond(5)
    1    
   121   
  12321  
 1234321 
123454321
 1234321 
  12321  
   121   
    1    

Upvotes: 3

user15104911
user15104911

Reputation: 1

for i in range (1,6):

for j in range(6-i):
    print(" ", end=" ")

for k in range(1,i):
    print(k, end = " ")

for l in range(i, 0, -1):
    print(l, end= " ")


print() 

for i in range (4,0,-1): for j in range(6-i): print(" ", end=" ")

for k in range(1,i):
    print(k, end = " ")

for l in range(i, 0, -1):
    print(l, end= " ")
print()

Upvotes: 0

Related Questions