1. Python / Говнокод #27446

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    # Калькулятор полных линейных неравенств
    
    # Модули
    from math import sqrt
    
    # Пояснение
    print('Это калькулятор полных линейных неравенств')
    print('Эти неравенства выглядят так: a*x^2 +- b*x +- c = 0')
    print('a, b и c - коэффиценты.\n')
    
    # Ввод коэффицентов
    a = int(input('Введите коэффицент a:'))
    b = int(input('Введите коэффицент b:'))
    c = int(input('Введите коэффицент c:'))
    r = 0
    D = 0
    # Решение: вид неравенства
    if b >= 0: 
        g = '+ '
    else:
        g = ''
    if c >= 0: 
        f = '+ '
    else:
        f = ''
    print('Так выглядит уравнение: ' + str(a) + 'x^2 ' + str(g) + str(b) + '*x ' + str(f) + str(c) + ' = 0')
    
    # Решение: коэффиценты и дискриминант
    print('Дискриминант(D) равен b^2 - 4 * a * c')
    print('Значит D = ' + str(b) + '^2 - 4 * ' + str(a) + ' * ' + str(c))
    b = int(b)
    a = int(a)
    c = int(c)
    D = b**2 - 4 * a * c
    print('D = ' + str(D))
    drt = sqrt(D)
    # Решение: ответ
    if D < 0:
        print('Ответ: Уравнение не имеет корней, так как дискриминант меньше нуля')
    elif D == 0:
        print('Уравнение имеет один корень: ')
        x = -b/(2*a)
        print('Корень уравнения: x = ' + str(x))
    elif D > 0: 
        print('Уравнение имеет два корня: ')
        x1 = (-b - drt)/2*a
        x2 = (-b + drt)/2*a
        print("Корни уравнения: x1 = " + str(x1) + ', x2 = ' + str(x2))
    else:
        r = 0

    Вот это чудо Я(гуманитарий) состряпал за 15 минут на второй день изучения питона. Ну как? Так ли худо?

    ni2kta, 31 Мая 2021

    Комментарии (96)
  2. Python / Говнокод #27441

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    from bs4 import BeautifulSoup
    import requests
    
    user = "**********"
    r = requests.get('https://www.last.fm/user/' + user)
    soup = BeautifulSoup(r.content, 'html.parser')
    page = soup.prettify()
    
    #Top artists
    print(
    page[int(page.find('’s top artists: ') + len('’s top artists: ')):int(page.find('. Get your own music profile at Last.fm')):]
    )
    
    #Top track
    print(
    ''.join(i if i != "+" else " " for i in (page[int(page.find('data-analytics-action="FeaturedTrackTrackName" href="/music/') + len('data-analytics-action="FeaturedTrackTrackName" href="/music/')):int(page.find('/_/', int(page.find('data-analytics-action="FeaturedTrackTrackName" href="/music/') + len('data-analytics-action="FeaturedTrackTrackName" href="/music/')))):] + " - " + page[int(page.find('/_/')) + 3:page.find('"', int(page.find('/_/'))):]))
    )

    Сбор с lastfm любимых исполнителей и любимого трека

    G-Chist, 28 Мая 2021

    Комментарии (108)
  3. Python / Говнокод #27426

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    from colorama import init, Fore, Back, Style
    init()
    print(Back.BLACK)
    print(Fore.RED)
    print(Style.NORMAL)
    print("Script mamoeba/Скрипт сделан")
    print("┌────────────────────────────────────┐")
    print("│Author : GovnoCode user                  │")
    print("│Github : https://:/│")
    print("└────────────────────────────────────┘")
    print("YouTube: utube")
    print("▄▀▄ █▄░▄█ ▀ █▄░█ ▄▀▄ ▄▀▄ █▀▄ ▐▌░▐▌ █▀▄ ▄▀▄")
    print("█▀█ █░█░█ █ █░▀█ █░█ █▀█ █░█ ░▀▄▀░ █▀█ █░█")
    print("▀░▀ ▀░░░▀ ▀ ▀░░▀ ░▀░ ▀░▀ ▀▀░ ░░▀░░ ▀▀░ ░▀░")
    print("Advertise Bot Amino")
    lz = []
    from concurrent.futures import ThreadPoolExecutor
    import concurrent.futures
    import amino
    def advertise(data):
        listusers = []
        for userId in data.profile.userId:
            listusers.append(userId)
        return listusers
        
    email = input("Email/Почта: ")
    password = input("Password/Пароль: ")
    msg = input("Message/Сообщение: ")
    client = amino.Client()
    client.login(email=email, password=password)
    clients = client.sub_clients(start=0, size=1000)
    for x, name in enumerate(clients.name, 1):
        print(f"{x}.{name}")
    communityid = clients.comId[int(input("Выберите сообщество/Select the community: "))-1]
    sub_client = amino.SubClient(comId=communityid, profile=client.profile)
    users = sub_client.get_online_users(size=1000)
    user = advertise(users)
    for i in lz:
            if i in user:
                user.remove(i)
         
            
    print("Sending Advertise")
    for _ in range(4000):
        with concurrent.futures.ThreadPoolExecutor(max_workers=40000) as executor:
            _ = [executor.submit(sub_client.start_chat, user, msg) for userId in user]
    
    print("Sending Advertise 2")
    for _ in range(4000):
        with concurrent.futures.ThreadPoolExecutor(max_workers=40000) as executor:

    Flow, 13 Мая 2021

    Комментарии (67)
  4. Python / Говнокод #27419

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    from enum import Enum
    from dataclasses import dataclass
    
    class Pathfind:
        __init__ = lambda self, maxmoves=9999: exec(f'self.maxmoves={maxmoves}')
        def pathfind(self, cells):
            i, found, ecords, path = 0, False, (0,0), list()
            while(not found):
                a = self.getbyval(cells, i)
                for n in [j for sub in [self.filterneighbors(self.getneighbors(cells, x[0], x[1])) for x in a] for j in sub]:
                    cells[n.ccoords[1]][n.ccoords[0]].value = i+1 if cells[n.ccoords[1]][n.ccoords[0]].value>(i+1) else cells[n.ccoords[1]][n.ccoords[0]].value
                    if cells[n.ccoords[1]][n.ccoords[0]].ctype == CellType.END: found, ecords = True, (n.ccoords[1],n.ccoords[0])
                if i<self.maxmoves: i+=1
                else: return False
            found, cpath = False, ecords
            while(not found):
                path.append(cpath)
                if cpath == self.getbyval(cells, 0)[0]: return path
                cell = list(filter(None, ([x if x.value==cells[cpath[0]][cpath[1]].value-1 else None for x in self.filterneighbors(self.getneighbors(cells, cpath[0], cpath[1]))])))[0]
                cpath = (cell.ccoords[1],cell.ccoords[0])
                
        listtocells = lambda self, lst: [[Cell(CellType(lst[y][x]), (x,y), 0 if lst[y][x]==2 else self.maxmoves) for x in range(len(lst[y]))] for y in range(len(lst))]
        getbyval = lambda self, cells, val: [(x, y) for x in range(len(cells)) for y in range(len(cells[x])) if cells[x][y].value == val]
        getneighbors = lambda self, cells, x, y: list(filter(None, [cells[x-1][y] if x>0 else None,cells[x+1][y] if x<len(cells)-1 else None,cells[x][y-1] if y>0 else None,cells[x][y+1] if y<len(cells[x])-1 else None]))
        filterneighbors = lambda self, cells: list(filter(lambda cell: False if (cell is None) or cell.ctype==CellType.WALL else True, cells))
    
    class CellType(Enum):
    	AIR, WALL, START, END = 0, 1, 2, 3
    
    @dataclass
    class Cell:
        ctype: CellType = CellType.AIR
        ccoords: tuple = (0,0)
        value: int = 0

    Максимально уёбищная реализация волнового алгоритма.

    Gehennom, 11 Мая 2021

    Комментарии (52)
  5. Python / Говнокод #27415

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    class Contacts(models.Model):
        GENDER_CHOICES = (('Male', 'male'), ('Female', 'female')) 
        # Мужик должен служить в армии и пахать в поле или на заводе, а баба - варить борщи и рожать детей...
        
        slug = models.SlugField(max_length=250, default='', blank=True)
        FirstName = models.CharField(max_length=50, blank=True, null=True)
        LastName = models.CharField(max_length=50, blank=True, null=True)
        MiddleName = models.CharField(max_length=50, blank=True, null=True)
        Photo = models.ImageField(upload_to='images/contacts/', blank=True, null=True)
        Sex = models.CharField(max_length=50, choices=GENDER_CHOICES, default='Male', blank=True, null=True)
        Birthday = models.DateField(blank=True, null=True)
        BirthdayDay = models.CharField(blank=True, null=True, max_length=2, validators=[validators.validate_date_day])
        BirthdayMonth = models.CharField(blank=True, null=True, max_length=2, validators=[validators.validate_date_month])
        BirthdayYear = models.CharField(blank=True, null=True, max_length=4)
        
        ContactPhone = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone])
        ContactPhoneCode = models.ForeignKey('PhoneNumberCode', on_delete=models.SET_NULL, related_name='ContactPhoneCode', blank=True, null=True)
        ContactPhoneNumber = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone_number])
        ContactPhoneLocal = models.BooleanField(default=False)
        
        WorkPhone = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone])
        WorkPhoneCode = models.ForeignKey('PhoneNumberCode', on_delete=models.SET_NULL, related_name='WorkPhoneCode', blank=True, null=True)
        WorkPhoneNumber = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone_number])
        WorkPhoneLocal = models.BooleanField(default=False)
        
        MobilePhone = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone])
        MobilePhoneCode = models.ForeignKey('PhoneNumberCode', on_delete=models.SET_NULL, related_name='MobilePhoneCode', blank=True, null=True)
        MobilePhoneNumber = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone_number])
        MobilePhoneLocal = models.BooleanField(default=False)
        
        WorkMobilePhone = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone])
        WorkMobilePhoneCode = models.ForeignKey('PhoneNumberCode', on_delete=models.SET_NULL, related_name='WorkMobilePhoneCode', blank=True, null=True)
        WorkMobilePhoneNumber = models.CharField(max_length=50, blank=True, null=True, validators=[validators.validate_phone_number])
        WorkMobilePhoneLocal = models.BooleanField(default=False)

    По Birthday была дана задача: "а сделай так, чтобы можно было выбирать не только полную дату, но и только день/только месяц/только год". А вот каким боком потребовалось выделять в отдельные поля составляющие телефонных номеров, даже для меня до сих пор загадка. Возможно, из той же оперы: "нужно, чтобы можно было вводить неполный номер". Как бы там ни было, можно было сделать отдельный custom field (в Джанго тем более для этого есть API - https://docs.djangoproject.com/en/3.2/howto/custom-model-fields/ ) или хотя бы сделать поле CharField-ом и уже в самой модели его парсить как надо (а перед перевыкладкой задампить данные и перегнать их в другой формат). Но нет, надо было нагородить еще полей под каждое место где встречалась дата. П..дец, какой же я макакой был...

    JaneBurt, 10 Мая 2021

    Комментарии (76)
  6. Python / Говнокод #27387

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    def main():
        pipe(int(input('Введите неотрицательное целое число: ')),   
             lambda n: (n, reduce(lambda x, y: x * y, range(1, n + 1))),   
             lambda tup: print(f'Факториал числа {tup[0]} равняется {tup[1]}'))

    Из https://habr.com/ru/post/555370/ (Функциональное ядро на Python).

    PolinaAksenova, 01 Мая 2021

    Комментарии (13)
  7. Python / Говнокод #27373

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    def generate_words(sample, phonemes, num=10): 
        global words, yd
        gen = True
        parens = 0
        r = random.random()
        word = ""
        i = 0
        while i < int(num):
            for j in range(0, len(sample)):
                if sample[j] == '(':
                    if gen:
                        gen = (random.randint(0,1) == 0)
                    if not gen:
                        parens += 1
                elif sample[j] == ')':
                    if not gen:
                        parens -= 1
                    if parens == 0:
                        gen = True
                elif sample[j] in phonemes.keys():
                    for n, phtype in enumerate(phonemes.keys()):
                        if gen and phtype == sample[j]:
                            #k = random.choice(phonemes[phtype])
                            n = yd.randomGen(phonemeRanks[phtype])
                            k = phonemes[phtype][n]
                            word += k
                elif gen:
                    word += sample[j]
                        
            if (not word in words) and (not isExceptional(word)):
                words.append(word)
    
            i += 1
            word = ""
    
    # ...
    
    """parsing sound changes rule with the notation X>Y/Z, where X is a set of source phonemes
    Y - a set of resulting phonemes, Z - a positional condition (optional)"""
    def parsePhNotation(inline):
        rule = inline.split('>')
        if (not len(rule) == 2):
            return []
    
        source = rule[0].split(',')
        final = rule[1].split('/')
    
        result = final[0].split(',')
        posCond = []
        rule = []
        if (len(final) > 2):
            return False
        elif (len(final) == 2):
            posCond = final[1].split('_')
            if (not len(posCond) == 2):
                return []
            posCond[0] = posCond[0].split('#')
            posCond[1] = posCond[1].split('#')
    
    
            
            if (len(posCond[0]) == 2) and len(posCond[0][0]) > 0:
                return []
            elif len(posCond[0]) == 2:
                rule.append(" "+posCond[0][1])
            else:
                rule.append(posCond[0][0])
    
            if (len(posCond[1]) == 2) and len(posCond[1][1]) > 0:
                return []
    
            rule.append(posCond[1][0])
            if len(posCond[1]) == 2:
                rule[1] += " "
            
            rule[0] = rule[0].split(",")
            rule[1] = rule[1].split(",")
    
        final = []
        if len(source) > len(result):
            for i in range(len(result)-1, len(source)-1):
                result.append("")
        elif len(source) < len(result):
            for i in range(len(source)-1, len(result)-1):
                source.append("")
    
        final.append(source)
        final.append(result)
        if (len(rule)>0):
            final.append(rule)
        return final

    Рекурсивный спуск, автомат с магазинной памятью, top-down parsing, bottom-up parsing? Не, не слышал. В свое время время делал вот такие самопальные алгоритмы для рандомной генерации слов по фонетическим шаблонам (типа "CV(C)", "VC" и т.д.) и фонетического преобразования слов и при попытке починить чета наступал на новые баги, т.к. не до конца понимал как вообще парсятся компьютерные языки.

    JaneBurt, 24 Апреля 2021

    Комментарии (1)
  8. Python / Говнокод #27361

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    import cowsay
    cowsay.cow('Hello World')
    
    
      ___________
    < Hello World >
      ===========
                    \
                     \
                       ^__^
                       (oo)\_______
                       (__)\       )\/\
                           ||----w |
                           ||     ||

    3_dar, 15 Апреля 2021

    Комментарии (244)
  9. Python / Говнокод #27354

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    """
    This module provides a function merge_sort, which is one of the simplest and the
    most robust sorting algorithms, being relatively fast, having (n*log(n))
    complexity. Also, this module counts the number of inversions in a given array.
    Usage: import this module and use the function merge_sort. The first element in
    a returned tuple shall be a sorted array, while the second one will be a number
    of inversions in the array.
    
    Copyright (C) 2021 Sergay Gayorgyevich.
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
    
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
    """
    
    import argparse
    
    def merge_sort(array : list) -> (list, int):
        """
        MergeSort algorithm with additional inversion counting.
        input: array.
        output: sorted array and number of inversions in it.
        """
    
        if len(array) <= 1:
            return (array, 0)
        elif len(array) == 2:
            if array[0] > array[1]:
                array[0], array[1] = array[1], array[0]
                return (array, 1)
            return (array, 0)
    
        mid = len(array) // 2
        left, left_inversions = merge_sort(array[:mid])
        right, right_inversions = merge_sort(array[mid:])
    
        merged, split_inversions = _merge(left, right)
        return (merged, right_inversions + left_inversions + split_inversions)
    
    def _merge(left_array : list, right_array : list) -> (list, int):
        """
        This function isn't supposed to be called, it's an inner function of the
        module, and not a part of its API! 
    
        The purpose of this function is to merge two arrays. Due to the nature of
        the MergeSort algorithm, it operates two arrays, both of which are sorted.
        input: two sotrted arrays.
        output: sorted array, consisting of elements of both operated arrays.
        """
    
        resulting_array = list()
        inversion_count = 0
        c_len = len(left_array) + len(right_array)
    
        for i in range(c_len):
            if (len(left_array) != 0) and (len(right_array) != 0):
                if left_array[0] > right_array[0]:
                    inversion_count += len(left_array)
                    resulting_array.append(right_array.pop(0))
                else:
                    resulting_array.append(left_array.pop(0))
            elif len(left_array) == 0:
                resulting_array.append(right_array.pop(0))
            elif len(right_array) == 0:
                resulting_array.append(left_array.pop(0))
    
        return (resulting_array[:], inversion_count)
    
    # For testing purposes only! Do not use in production!
    if __name__ == '__main__':
        DESC = "Sort an array and print an amount of inversions it has." # Description for argparse.
        argparser = argparse.ArgumentParser(description = DESC)
        argparser.add_argument("elements", type = int, nargs = '+', help = "A list to be sorted.")
        args = argparser.parse_args()
        print(merge_sort(args.elements))

    Изучаю алгоритм "Сортировка Слиянием".

    KoWe4Ka_l7porpaMMep, 12 Апреля 2021

    Комментарии (159)
  10. Python / Говнокод #27351

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    """
    A module for printing funny frames.
    Copyright (C) 2021 Ingostnus.
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.
    
    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
    """
    
    from math import sqrt
    
    _str = "sample"                  # String to be turned into a funny frame.
    _sep = ' '                       # Separator, i.e. a string to be inserted between each letter of the _str.
    _vertical_separator_mode = 'F'   # Determines whether separator should be printed between each row.
                                     # ... 'F' --> off. 'T' --> on.
    
    def get_user_input() -> None:
        """
        This function lets user input desired values and override the defaults.
        """
        global _str; _str = str(input("String: "))
        global _sep; _sep = str(input("Character: "))
        global _vertical_separator_mode; _vertical_separator_mode = str((input("VSM (T/F):")))
        if _vertical_separator_mode == 'T':
            print("VMS is ON!!!")
    
    def print_frame(printer = print) -> list:
        """
        This function is designed for printing a frame. Custom printer function
        may be supplied to process the output in a specific way.
        """
    
        buffer_len = (len(_str) + len(_sep) * (len(_str) - 1))**2
    
        # First line.
        printer(''.join([_str[i] + _sep if i < (len(_str) - 1) else _str[-1] for i in range(len(_str))]))
        
        # Second -- pre last lines.
        empty_space = ' ' * (int(sqrt(buffer_len)) - 2)
        for i in range(1, len(_str) - 1):
            # If vertical separator mode is toggled, print vertical separator.
            if _vertical_separator_mode == 'T':
                printer(_sep + empty_space + _sep)
            printer(_str[i] + empty_space + _str[-(i + 1)])
        
        # Last line.
        printer(''.join([_str[-(i + 1)] + _sep if i < (len(_str) - 1) else _str[0] for i in range(len(_str))]))
    
    # To give the best perfomance and flexibility, this module should be used as
    # an imported library. Though, its basic functionality can be used even if
    # it's executed directly.
    if __name__ == '__main__':
        get_user_input()
        print_frame()

    Переписала код https://govnokod.ru/27348 на питон, добавив чуть-чуть улучшений и немноже4ко документацци.

    KoWe4Ka_l7porpaMMep, 11 Апреля 2021

    Комментарии (26)