TheAlgorithms-Python

Форк
0
/
magicdiamondpattern.py 
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)
5
def floyd(n):
6
    """
7
    Print the upper half of a diamond pattern with '*' characters.
8

9
    Args:
10
        n (int): Size of the pattern.
11

12
    Examples:
13
        >>> floyd(3)
14
        '  * \\n * * \\n* * * \\n'
15

16
        >>> floyd(5)
17
        '    * \\n   * * \\n  * * * \\n * * * * \\n* * * * * \\n'
18
    """
19
    result = ""
20
    for i in range(n):
21
        for _ in range(n - i - 1):  # printing spaces
22
            result += " "
23
        for _ in range(i + 1):  # printing stars
24
            result += "* "
25
        result += "\n"
26
    return result
27

28

29
# Function to print lower half of diamond (pyramid)
30
def reverse_floyd(n):
31
    """
32
    Print the lower half of a diamond pattern with '*' characters.
33

34
    Args:
35
        n (int): Size of the pattern.
36

37
    Examples:
38
        >>> reverse_floyd(3)
39
        '* * * \\n * * \\n  * \\n   '
40

41
        >>> reverse_floyd(5)
42
        '* * * * * \\n * * * * \\n  * * * \\n   * * \\n    * \\n     '
43
    """
44
    result = ""
45
    for i in range(n, 0, -1):
46
        for _ in range(i, 0, -1):  # printing stars
47
            result += "* "
48
        result += "\n"
49
        for _ in range(n - i + 1, 0, -1):  # printing spaces
50
            result += " "
51
    return result
52

53

54
# Function to print complete diamond pattern of "*"
55
def pretty_print(n):
56
    """
57
    Print a complete diamond pattern with '*' characters.
58

59
    Args:
60
        n (int): Size of the pattern.
61

62
    Examples:
63
        >>> pretty_print(0)
64
        '       ...       ....        nothing printing :('
65

66
        >>> pretty_print(3)
67
        '  * \\n * * \\n* * * \\n* * * \\n * * \\n  * \\n   '
68
    """
69
    if n <= 0:
70
        return "       ...       ....        nothing printing :("
71
    upper_half = floyd(n)  # upper half
72
    lower_half = reverse_floyd(n)  # lower half
73
    return upper_half + lower_half
74

75

76
if __name__ == "__main__":
77
    import doctest
78

79
    doctest.testmod()
80

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.