forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
magicdiamondpattern.py
79 lines (61 loc) · 2 KB
/
magicdiamondpattern.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Python program for generating diamond pattern in Python 3.7+
# Function to print upper half of diamond (pyramid)
def floyd(n):
"""
Print the upper half of a diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> floyd(3)
' * \\n * * \\n* * * \\n'
>>> floyd(5)
' * \\n * * \\n * * * \\n * * * * \\n* * * * * \\n'
"""
result = ""
for i in range(n):
for _ in range(n - i - 1): # printing spaces
result += " "
for _ in range(i + 1): # printing stars
result += "* "
result += "\n"
return result
# Function to print lower half of diamond (pyramid)
def reverse_floyd(n):
"""
Print the lower half of a diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> reverse_floyd(3)
'* * * \\n * * \\n * \\n '
>>> reverse_floyd(5)
'* * * * * \\n * * * * \\n * * * \\n * * \\n * \\n '
"""
result = ""
for i in range(n, 0, -1):
for _ in range(i, 0, -1): # printing stars
result += "* "
result += "\n"
for _ in range(n - i + 1, 0, -1): # printing spaces
result += " "
return result
# Function to print complete diamond pattern of "*"
def pretty_print(n):
"""
Print a complete diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> pretty_print(0)
' ... .... nothing printing :('
>>> pretty_print(3)
' * \\n * * \\n* * * \\n* * * \\n * * \\n * \\n '
"""
if n <= 0:
return " ... .... nothing printing :("
upper_half = floyd(n) # upper half
lower_half = reverse_floyd(n) # lower half
return upper_half + lower_half
if __name__ == "__main__":
import doctest
doctest.testmod()