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