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 s
Solution 1:
The following can do this concisely using a helper function:
defup_and_down(n): # 1,2, ..., n, ..., 2, 1return (*range(1, n), *range(n, 0, -1))
defdiamond(n):
for i in up_and_down(n):
print((n-i)*' ', *up_and_down(i), sep='')
>>> diamond(5)
11211232112343211234543211234321123211211
Solution 2:
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()
Solution 3:
Another (very simple) way to handle this is to take advantage of:
- The call stack.
- 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:
defdiamond(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.
Post a Comment for "Print A Diamond Of Numbers In Python"