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

    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
    import cowsay
    cowsay.cow('Hello World')
    
    
      ___________
    < Hello World >
      ===========
                    \
                     \
                       ^__^
                       (oo)\_______
                       (__)\       )\/\
                           ||----w |
                           ||     ||

    3_dar, 15 Апреля 2021

    Комментарии (243)
  2. 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

    Комментарии (158)
  3. 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)
  4. Python / Говнокод #27347

    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
    def karatsuba_multiplication(x : int, y : int) -> int:
        sx, sy = map(lambda x: '0' + str(x) if len(str(x)) % 2 != 0 else str(x), (x, y))
        return _karatsuba_multiplication(sx, sy, max(len(sx), len(sy)))
    
    def _prepend_nils(string : str, amount_of_nils : int) -> str:
        return ('0' * amount_of_nils + string)
    
    def _karatsuba_multiplication(x : str, y : str, n : int) -> int:
        x, y = map(lambda x: _prepend_nils(x, (n - len(x))), (x, y))
    
        if (n == 1):
            return (int(x) * int(y))
    
        mid = n // 2
        a, b = int(x[:mid]), int(x[mid:])
        c, d = int(y[:mid]), int(y[mid:])
    
        p = a + b
        q = c + d
        ac = _karatsuba_multiplication(str(a), str(c), max(len(str(a)), len(str(c))))
        bd = _karatsuba_multiplication(str(b), str(d), max(len(str(b)), len(str(d))))
        pq = _karatsuba_multiplication(str(p), str(q), max(len(str(p)), len(str(q))))
        adbc = pq - ac - bd
        return 10**n * ac + 10**(mid + n % 2) * adbc + bd

    Как-то не очень получилось...

    JloJle4Ka, 10 Апреля 2021

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

    +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
    18. 18
    19. 19
    20. 20
    def ForQueryInAddr(query, addr):
    	global listed, primalsource
    	print("Searcing in: "+addr)
    	html = requests.get(addr,proxies=proxies).text
    	if (query.lower() in html.lower()):
    		print("==============================================")
    		print("Query found in: "+addr)
    		print("==============================================")
    	if ("<html>" in html or "<head>" in html):
    		data = PyQuery(html)
    		links = data('a')
    		for link in links:
    			ahref = link.attrib['href']
    			#print("Found: "+ahref)
    			if (ahref not in listed):
    				if (ahref[0].lower() == "h"):
    					if (primalsource in ahref):
    						if (ahref[-3:].lower() not in filetypes and ahref[-4:].lower() not in filetypes and ahref[-5:].lower() not in filetypes):
    							listed.append(ahref)
    							ForQueryInAddr(query, ahref)

    https://github.com/Dev1lroot/OnionSearch/blob/master/main.py

    PolinaAksenova, 06 Апреля 2021

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

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    match group_shapes():
        case [], [point := Point(x, y), *other]:
            print(f"Got {point} in the second group")
            process_coordinates(x, y)

    https://www.python.org/dev/peps/pep-0622/

    DypHuu_niBEHb, 31 Марта 2021

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

    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
    def luhn(self):
            all_sum = 0
            self.__card_number = str(self.__card_number)
            self.__card_number = list(self.__card_number)
            for element in range(len(self.__card_number)):
                if element % 2 == 0:
                    self.__card_number[element] = int(self.__card_number[element]) * 2
                    if self.__card_number[element] > 9:
                        number = self.__card_number[element]
                        self.__card_number[element] = number // 100 + number // 10 % 10 + number % 10  # sum digits of number
                self.__card_number[element] = int(self.__card_number[element])
                all_sum += self.__card_number[element]
            checksum = 0
            while checksum < 10:
                if all_sum % 10 == 0:
                    checksum = str(checksum)
                    break
                else:
                    all_sum += 1
                    checksum += 1
            self.i = str(self.i)
            self.i = list(self.i)
            self.i.append(checksum)
            self.__card_number = self.i
     
            self.__card_number = "".join(self.__card_number)

    Для преокта нужен был алгоритм луна, чтобы создать в конце контрольную сумму. При написании проебался, что мне card_number нужно просто добавить 1 цифру, а не менять его и по этому просто добавил костыль в виде i.

    warzon131, 27 Марта 2021

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

    0

    1. 1
    2. 2
    def IsZIPFile(filename):
        return filename.lower().endswith('.zip')

    ибааааать!

    Petro-san, 10 Марта 2021

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

    0

    1. 1
    2. 2
    3. 3
    4. 4
    XRU = "XRU"
    PITUH = "PITUH",
    KUROCHKA = "KUROCHKA"
    PETUH = PITUH.replace('I', 'E')

    Traceback (most recent call last):
    File "./prog.py", line 4, in <module>
    AttributeError: 'tuple' object has no attribute 'replace'

    3_dar, 02 Марта 2021

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

    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
    import math
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--type")
    parser.add_argument("--principal", type=int)
    parser.add_argument("--periods", type=int)
    parser.add_argument("--interest", type=float)
    parser.add_argument("--payment", type=float)
    
    args = parser.parse_args()
    
    choose = args.type
    p = args.principal
    n = args.periods
    i = args.interest
    a = args.payment
    
    if i is None or p is None and a is None:
        print("Incorrect parameters.")
        exit(0)
    
    i = (i * 0.01) / (12 * 1)
    
    if choose == "diff":
        m = 1
        overpayment_all = 0
        while m <= n:
            d = math.ceil(p / n + i * (p - ((p * (m - 1)) / n)))
            m += 1
            overpayment_all += d
            print(f"Month {m - 1}: payment is {d}")
        print()
        print(f"Overpayment = {overpayment_all - p}")
    
    elif choose == "annuity" and a is None:
        a = math.ceil(p * (i * math.pow((1 + i), n)) / (math.pow((1 + i), n) - 1))
        print(f"Your monthly payment = {a}!")
        over = a * n - p
        print(f"Overpayment = {math.ceil(over)}")
    
    elif choose == "annuity" and p is None:
        p = int(a / (i * math.pow(1 + i, n) / (math.pow(1 + i, n) - 1)))
        print(f"Your loan principal = {p}!")
        m = 1
        over = a * n - p
        print(f"Overpayment = {math.ceil(over)}")
    
    elif choose == "annuity":
        n = math.ceil(math.log(a / (a - i * p), 1 + i))
        zxc = math.ceil(math.log(a / (a - i * p), 1 + i))
        years = 0
        while n >= 12:
            n -= 12
            years += 1
        if years == 0:
            print(f"It will take {n} months to repay this loan!")
            over = a * zxc - p
            print(f"Overpayment = {math.ceil(over)}")
        elif n == 0:
            print(f"It will take {years} years to repay this loan!")
            over = a * zxc - p
            print(f"Overpayment = {math.ceil(over)}")
        else:
            print(f"It will take {years} years and {n} months to repay this loan!")
            over = a * zxc - p
            print(f"Overpayment = {math.ceil(over)}")

    Ебучий универ и ебучее задание на питоне. Всё было бы збс, если бы не математика.
    Прога считает проценты, бабки, переплаты и чёт ещё, наверное

    warzon131, 25 Февраля 2021

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