From d6a818ad3a5c1966af112e8258fdb46142e39a9f Mon Sep 17 00:00:00 2001 From: Sourcery AI Date: Fri, 30 Jun 2023 12:44:26 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- Python/0_algorithms/hw_1/08_leap_year.py | 19 ++++--- Python/0_algorithms/hw_2/02_even_odd.py | 2 +- Python/0_algorithms/hw_2/03_revers.py | 2 +- Python/0_algorithms/hw_2/07_teorema.py | 5 +- Python/0_algorithms/hw_2/09_max_sum.py | 4 +- Python/0_algorithms/hw_3/01_99_div_2-9.py | 5 +- Python/0_algorithms/hw_3/02_even_value.py | 5 +- Python/0_algorithms/hw_3/04_max_count.py | 5 +- Python/0_algorithms/hw_3/05_max_below_zero.py | 6 +- .../hw_3/06_sum_betwen_min_max.py | 4 +- Python/0_algorithms/hw_3/09_max_in_mins.py | 6 +- Python/0_algorithms/hw_4/1_counter.py | 18 +++--- Python/0_algorithms/hw_4/1_deque.py | 2 +- Python/0_algorithms/hw_4/1_namedtuple.py | 6 +- Python/0_algorithms/hw_4/2_defaultdict.py | 4 +- Python/0_algorithms/hw_4/2_deque.py | 8 +-- .../0_algorithms/hw_4/2_namedtuple_deque.py | 15 +++-- .../0_algorithms/hw_4/2_ordereddict_deque.py | 2 +- Python/0_algorithms/hw_4/t_sieve.py | 5 +- Python/0_algorithms/hw_5/2_loop_sample.py | 6 +- Python/0_algorithms/hw_6/02_even_odd.py | 4 +- Python/0_algorithms/hw_6/_1.py | 2 +- Python/0_algorithms/hw_6/_2.py | 57 ++++++++++--------- Python/0_algorithms/hw_6/_3.py | 7 +-- Python/0_algorithms/hw_6/_4.py | 10 ++-- Python/0_algorithms/hw_6/_5.py | 6 +- Python/0_algorithms/hw_7/5_Haffman.py | 9 ++- Python/1_home/2.py | 8 +-- Python/1_home/3.py | 17 +++--- Python/1_home/4.py | 9 ++- 30 files changed, 111 insertions(+), 147 deletions(-) diff --git a/Python/0_algorithms/hw_1/08_leap_year.py b/Python/0_algorithms/hw_1/08_leap_year.py index 066a663..fc8ec18 100644 --- a/Python/0_algorithms/hw_1/08_leap_year.py +++ b/Python/0_algorithms/hw_1/08_leap_year.py @@ -12,14 +12,15 @@ print("Обычный") else: print("Високосный") - + # длинный способ -if year % 4 != 0: - print("Обычный") -elif year % 100 == 0: - if year % 400 == 0: - print("Високосный") - else: - print("Обычный") +if ( + year % 4 == 0 + and year % 100 == 0 + and year % 400 == 0 + or year % 4 == 0 + and year % 100 != 0 +): + print("Високосный") else: - print("Високосный") \ No newline at end of file + print("Обычный") \ No newline at end of file diff --git a/Python/0_algorithms/hw_2/02_even_odd.py b/Python/0_algorithms/hw_2/02_even_odd.py index 9d4f39d..5f762c3 100644 --- a/Python/0_algorithms/hw_2/02_even_odd.py +++ b/Python/0_algorithms/hw_2/02_even_odd.py @@ -14,7 +14,7 @@ even += 1 else: odd += 1 - num = num // 10 + num //= 10 print(f"четных - {even}, нечетных - {odd}") diff --git a/Python/0_algorithms/hw_2/03_revers.py b/Python/0_algorithms/hw_2/03_revers.py index c23813a..05d4f1b 100644 --- a/Python/0_algorithms/hw_2/03_revers.py +++ b/Python/0_algorithms/hw_2/03_revers.py @@ -11,7 +11,7 @@ result = 0 while num > 0: result = result * 10 + num % 10 - num = num // 10 + num //= 10 print(result) # вариант 2 diff --git a/Python/0_algorithms/hw_2/07_teorema.py b/Python/0_algorithms/hw_2/07_teorema.py index bd54567..dd40445 100644 --- a/Python/0_algorithms/hw_2/07_teorema.py +++ b/Python/0_algorithms/hw_2/07_teorema.py @@ -9,10 +9,7 @@ def sum_natural(n): assert n < 999, 'Слишком большое число' - if n == 1: - return n - sum_n = n + sum_natural(n - 1) - return sum_n + return n if n == 1 else n + sum_natural(n - 1) n = int(input('Введите любое натуральное число: ')) diff --git a/Python/0_algorithms/hw_2/09_max_sum.py b/Python/0_algorithms/hw_2/09_max_sum.py index f106da9..22a83c7 100644 --- a/Python/0_algorithms/hw_2/09_max_sum.py +++ b/Python/0_algorithms/hw_2/09_max_sum.py @@ -8,9 +8,7 @@ def sum_digits(number): - if number < 10: - return number - return number % 10 + sum_digits(number // 10) + return number if number < 10 else number % 10 + sum_digits(number // 10) num = int(input('Введите натуральное число. Ноль - выйти ')) diff --git a/Python/0_algorithms/hw_3/01_99_div_2-9.py b/Python/0_algorithms/hw_3/01_99_div_2-9.py index cfaade8..5e9b920 100644 --- a/Python/0_algorithms/hw_3/01_99_div_2-9.py +++ b/Python/0_algorithms/hw_3/01_99_div_2-9.py @@ -7,10 +7,7 @@ END_DIV = 9 # вариант 1 for i in range(START_DIV, END_DIV + 1): - frequency = 0 - for j in range(START_NUM, END_NUM + 1): - if j % i == 0: - frequency += 1 + frequency = sum(1 for j in range(START_NUM, END_NUM + 1) if j % i == 0) print(f'Числу {i} кратно {frequency} чисел') # вариант 2 diff --git a/Python/0_algorithms/hw_3/02_even_value.py b/Python/0_algorithms/hw_3/02_even_value.py index 71060bc..ac959f6 100644 --- a/Python/0_algorithms/hw_3/02_even_value.py +++ b/Python/0_algorithms/hw_3/02_even_value.py @@ -11,10 +11,7 @@ array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array) -result = [] -for i in range(len(array)): - if array[i] % 2 == 0: - result.append(i) +result = [i for i in range(len(array)) if array[i] % 2 == 0] print(f'Индексы чётных элементов: {result}') result_new = [i for i in range(len(array)) if array[i] % 2 == 0] diff --git a/Python/0_algorithms/hw_3/04_max_count.py b/Python/0_algorithms/hw_3/04_max_count.py index 1fce854..fdc690b 100644 --- a/Python/0_algorithms/hw_3/04_max_count.py +++ b/Python/0_algorithms/hw_3/04_max_count.py @@ -11,10 +11,7 @@ num = array[0] frequency = 1 for i in range(len(array)): - spam = 1 - for j in range(i + 1, len(array)): - if array[i] == array[j]: - spam += 1 + spam = 1 + sum(1 for j in range(i + 1, len(array)) if array[i] == array[j]) if spam > frequency: frequency = spam num = array[i] diff --git a/Python/0_algorithms/hw_3/05_max_below_zero.py b/Python/0_algorithms/hw_3/05_max_below_zero.py index 2f5d7e8..e520b95 100644 --- a/Python/0_algorithms/hw_3/05_max_below_zero.py +++ b/Python/0_algorithms/hw_3/05_max_below_zero.py @@ -9,16 +9,12 @@ array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(array) -# вариант 1 -i = 0 index = -100500 -while i < len(array): # или for i in range(len(array)): +for i in range(len(array)): # или for i in range(len(array)): if array[i] < 0 and index == -100500: index = i elif 0 > array[i] > array[index]: index = i - i += 1 - if index != -100500: print(f'Максимальное отрицательное число {array[index]} ' f'находится в ячейке {index}') diff --git a/Python/0_algorithms/hw_3/06_sum_betwen_min_max.py b/Python/0_algorithms/hw_3/06_sum_betwen_min_max.py index 86e509a..eb45930 100644 --- a/Python/0_algorithms/hw_3/06_sum_betwen_min_max.py +++ b/Python/0_algorithms/hw_3/06_sum_betwen_min_max.py @@ -23,7 +23,5 @@ print(f'Левая граница: {array[idx_min]}\n' f'Правая граница: {array[idx_max]}') -summ = 0 -for i in range(idx_min + 1, idx_max): - summ += array[i] +summ = sum(array[i] for i in range(idx_min + 1, idx_max)) print(f'Сумма = {summ}') diff --git a/Python/0_algorithms/hw_3/09_max_in_mins.py b/Python/0_algorithms/hw_3/09_max_in_mins.py index dcdc80b..6f18072 100644 --- a/Python/0_algorithms/hw_3/09_max_in_mins.py +++ b/Python/0_algorithms/hw_3/09_max_in_mins.py @@ -16,9 +16,9 @@ for j in range(len(matrix[0])): min_ = matrix[0][j] - for i in range(len(matrix)): - if matrix[i][j] < min_: - min_ = matrix[i][j] + for item in matrix: + if item[j] < min_: + min_ = item[j] if max_ is None or max_ < min_: max_ = min_ diff --git a/Python/0_algorithms/hw_4/1_counter.py b/Python/0_algorithms/hw_4/1_counter.py index bb19e19..a7ec843 100644 --- a/Python/0_algorithms/hw_4/1_counter.py +++ b/Python/0_algorithms/hw_4/1_counter.py @@ -2,14 +2,12 @@ n = int(input("Введите количество предприятий для расчета прибыли: ")) -d = dict() -a = 1 -for i in range(n): +d = {} +for a, _ in enumerate(range(n), start=1): name = input("Введите название предприятия: ") pr = input("через пробел введите прибыль данного предприятия\nза каждый квартал(Всего 4 квартала): ") profit = pr.split(" ") d[name] = profit - a += 1 print() fab = collections.Counter(d) @@ -17,20 +15,18 @@ sc = [] b = 0 t = 0 -for i in fab: - summ = 0 - for j in fab[i]: - summ += int(j) +for i, value in fab.items(): + summ = sum(int(j) for j in value) fab[i] = summ t += summ b += 1 sec = t / b -print("Средняя годовая прибыль всех предприятий: " + str(sec)) +print(f"Средняя годовая прибыль всех предприятий: {str(sec)}") bigger = [] smaller = [] -for i in fab: - if int(fab[i]) >= sec: +for i, value_ in fab.items(): + if int(value_) >= sec: bigger.append(i) else: smaller.append(i) diff --git a/Python/0_algorithms/hw_4/1_deque.py b/Python/0_algorithms/hw_4/1_deque.py index 3ffd58f..ace55a8 100644 --- a/Python/0_algorithms/hw_4/1_deque.py +++ b/Python/0_algorithms/hw_4/1_deque.py @@ -12,7 +12,7 @@ org_lst.append(new_org) print("-" * 5) -avg = sum([i.get('q_sum', 0.0) for i in org_lst]) / n +avg = sum(i.get('q_sum', 0.0) for i in org_lst) / n print(f"Предприятия с общей прибылью выше среднего (среднее = {avg:.2f}):", ", ".join([f"{i.get('name')} ({i.get('q_sum')})" for i in org_lst if i.get('q_sum', 0.0) > avg])) diff --git a/Python/0_algorithms/hw_4/1_namedtuple.py b/Python/0_algorithms/hw_4/1_namedtuple.py index 582b450..7d4eda2 100644 --- a/Python/0_algorithms/hw_4/1_namedtuple.py +++ b/Python/0_algorithms/hw_4/1_namedtuple.py @@ -4,7 +4,7 @@ companies = namedtuple("Company", " name period_1 period_2 period_3 period_4") profit_aver = {} -for i in range(n): +for _ in range(n): company = companies(name=input("Введите название предприятия: "), period_1=int(input("Введите прибыль за первый квартал: ")), period_2=int(input("Введите прибыль за второй квартал: ")), @@ -13,9 +13,7 @@ profit_aver[company.name] = (company.period_1 + company.period_2 + company.period_3 + company.period_4) / 4 -total_aver = 0 -for value in profit_aver.values(): - total_aver += value +total_aver = sum(profit_aver.values()) total_aver = total_aver / n for key, value in profit_aver.items(): diff --git a/Python/0_algorithms/hw_4/2_defaultdict.py b/Python/0_algorithms/hw_4/2_defaultdict.py index 6c6fa69..2b69279 100644 --- a/Python/0_algorithms/hw_4/2_defaultdict.py +++ b/Python/0_algorithms/hw_4/2_defaultdict.py @@ -15,10 +15,10 @@ nums = collections.defaultdict(list) for d in range(2): n = input("Введите %d-е натуральное шестнадцатиричное число: " % (d+1)) - nums["%s-%s" % (d+1, n)] = list(n) + nums[f"{d + 1}-{n}"] = list(n) print(nums) -sum = sum([int(''.join(i), 16) for i in nums.values()]) +sum = sum(int(''.join(i), 16) for i in nums.values()) print("Сумма: ", list('%X' % sum)) mult = functools.reduce(lambda a, b: a * b, [int(''.join(i), 16) for i in nums.values()]) diff --git a/Python/0_algorithms/hw_4/2_deque.py b/Python/0_algorithms/hw_4/2_deque.py index cd3cd63..d01e588 100644 --- a/Python/0_algorithms/hw_4/2_deque.py +++ b/Python/0_algorithms/hw_4/2_deque.py @@ -13,16 +13,16 @@ def hex_sum(x, y): - x = "".join([i for i in x]) - y = "".join([i for i in y]) + x = "".join(list(x)) + y = "".join(list(y)) s = hex((int(float.fromhex(x) + float.fromhex(y)))) s = deque(s[2::].upper()) print("Сумма:", s) def hex_mul(x, y): - x = "".join([i for i in x]) - y = "".join([i for i in y]) + x = "".join(list(x)) + y = "".join(list(y)) s = hex((int(float.fromhex(x) * float.fromhex(y)))) s = deque(s[2::].upper()) print("Произведение:", s) diff --git a/Python/0_algorithms/hw_4/2_namedtuple_deque.py b/Python/0_algorithms/hw_4/2_namedtuple_deque.py index 9a630c5..90bccc8 100644 --- a/Python/0_algorithms/hw_4/2_namedtuple_deque.py +++ b/Python/0_algorithms/hw_4/2_namedtuple_deque.py @@ -26,14 +26,13 @@ def to_dec(self, x): def to_hex(self, x): if x < 16: return [str(x)] - else: - r = deque() - while x > 15: - d = x % 16 - r.appendleft(str(d) if d < 10 else self.hex_letters._fields[d-10]) - x = x // 16 - r.appendleft(str(x) if x < 10 else self.hex_letters._fields[x-10]) - return list(r) + r = deque() + while x > 15: + d = x % 16 + r.appendleft(str(d) if d < 10 else self.hex_letters._fields[d-10]) + x = x // 16 + r.appendleft(str(x) if x < 10 else self.hex_letters._fields[x-10]) + return list(r) a = input("Введите перове число в шестнадцатиричном формате: ").upper() diff --git a/Python/0_algorithms/hw_4/2_ordereddict_deque.py b/Python/0_algorithms/hw_4/2_ordereddict_deque.py index 11521e8..20423c6 100644 --- a/Python/0_algorithms/hw_4/2_ordereddict_deque.py +++ b/Python/0_algorithms/hw_4/2_ordereddict_deque.py @@ -17,7 +17,7 @@ def hex_to_decimal(num): for key, value in enumerate(HEX_NUMS): hex_number[value] = key - return sum([hex_number[j] * (16 ** i) for i, j in enumerate(num)]) + return sum(hex_number[j] * (16 ** i) for i, j in enumerate(num)) def decimal_to_hex(num): diff --git a/Python/0_algorithms/hw_4/t_sieve.py b/Python/0_algorithms/hw_4/t_sieve.py index 184d4ed..f685ad7 100644 --- a/Python/0_algorithms/hw_4/t_sieve.py +++ b/Python/0_algorithms/hw_4/t_sieve.py @@ -18,12 +18,11 @@ def prime(num): 664579: 10 ** 7, 5761455: 10 ** 8, } - for key in pi_func.keys(): + for key, size in pi_func.items(): if num <= key: - size = pi_func[key] break - array = [i for i in range(size)] + array = list(range(size)) array[1] = 0 for i in range(2, size): diff --git a/Python/0_algorithms/hw_5/2_loop_sample.py b/Python/0_algorithms/hw_5/2_loop_sample.py index 2e21b7d..3ff4de6 100644 --- a/Python/0_algorithms/hw_5/2_loop_sample.py +++ b/Python/0_algorithms/hw_5/2_loop_sample.py @@ -4,11 +4,9 @@ all_comp = [] Comp = namedtuple('Comp', 'name, p1, p2, p3, p4, total') num = int(input('num = ')) -for i in range(num): +for _ in range(num): name = input('name = ') - spam = [] - for j in range(1, 5): - spam.append(int(input(f'{j} = '))) + spam = [int(input(f'{j} = ')) for j in range(1, 5)] all_comp.append(Comp(name, *spam, sum(spam))) print(all_comp) diff --git a/Python/0_algorithms/hw_6/02_even_odd.py b/Python/0_algorithms/hw_6/02_even_odd.py index 4ee2bc9..6e11d01 100644 --- a/Python/0_algorithms/hw_6/02_even_odd.py +++ b/Python/0_algorithms/hw_6/02_even_odd.py @@ -12,7 +12,7 @@ even += 1 else: odd += 1 - num = num // 10 + num //= 10 print(sys.getsizeof(even)) print(sys.getsizeof(odd)) @@ -29,7 +29,7 @@ even += 1 else: odd += 1 - num = num // 10 + num //= 10 sum_ += sys.getsizeof(even) sum_ += sys.getsizeof(odd) diff --git a/Python/0_algorithms/hw_6/_1.py b/Python/0_algorithms/hw_6/_1.py index fcf09d6..9264db0 100644 --- a/Python/0_algorithms/hw_6/_1.py +++ b/Python/0_algorithms/hw_6/_1.py @@ -37,7 +37,7 @@ def bubble_sort_upd(orig_list): return orig_list -orig_list = [random.randint(-100, 100) for i in range(10)] +orig_list = [random.randint(-100, 100) for _ in range(10)] print(timeit.timeit("bubble_sort(orig_list)", setup="from __main__ import bubble_sort, orig_list", number=1000000)) print(timeit.timeit("bubble_sort_upd(orig_list)", setup="from __main__ import bubble_sort_upd, orig_list", number=1000000)) diff --git a/Python/0_algorithms/hw_6/_2.py b/Python/0_algorithms/hw_6/_2.py index 784165a..f7065b1 100644 --- a/Python/0_algorithms/hw_6/_2.py +++ b/Python/0_algorithms/hw_6/_2.py @@ -8,39 +8,40 @@ def merge_sort(alist): - if len(alist)>1: - mid = len(alist)//2 - lefthalf = alist[:mid] - righthalf = alist[mid:] - - merge_sort(lefthalf) - merge_sort(righthalf) - - i=0 - j=0 - k=0 - while i min_num2: min_num, min_num2 = min_num2, min_num - for i in range(len(a)): - if a[i] < min_num: + for item in a: + if item < min_num: min_num2 = min_num - min_num = a[i] - elif a[i] < min_num2: - min_num2 = a[i] + min_num = item + elif item < min_num2: + min_num2 = item print("Два наименьших элемента:", min_num, min_num2) del a diff --git a/Python/0_algorithms/hw_6/_5.py b/Python/0_algorithms/hw_6/_5.py index c4b6c9f..bcdeabd 100644 --- a/Python/0_algorithms/hw_6/_5.py +++ b/Python/0_algorithms/hw_6/_5.py @@ -42,17 +42,15 @@ def simple(i): # Вариант 2 (решето Эратосфена) @profile def eratosfen(i): - n = 2 l = 10000 - sieve = [x for x in range(l)] + sieve = list(range(l)) sieve[1] = 0 - while n < l: + for n in range(2, l): if sieve[n] != 0: m = n*2 while m < l: sieve[m] = 0 m += n - n += 1 return [p for p in sieve if p != 0][i-1] i = int(input('Введите порядковый номер искомого простого числа:')) diff --git a/Python/0_algorithms/hw_7/5_Haffman.py b/Python/0_algorithms/hw_7/5_Haffman.py index 7032561..23d8087 100644 --- a/Python/0_algorithms/hw_7/5_Haffman.py +++ b/Python/0_algorithms/hw_7/5_Haffman.py @@ -21,10 +21,9 @@ def haffman_tree(s): for i, _count in enumerate(sorted_elements): if weight > _count[1]: continue - else: - # Вставляем объеденный элемент - sorted_elements.insert(i, (comb, weight)) - break + # Вставляем объеденный элемент + sorted_elements.insert(i, (comb, weight)) + break else: # Добавляем объеденный корневой элемент после # завершения работы цикла @@ -37,7 +36,7 @@ def haffman_tree(s): return sorted_elements[0][0] -code_table = dict() +code_table = {} def haffman_code(tree, path=''): diff --git a/Python/1_home/2.py b/Python/1_home/2.py index dffa955..b2cd647 100644 --- a/Python/1_home/2.py +++ b/Python/1_home/2.py @@ -26,11 +26,11 @@ x = int(input()) a = x % 10 -x = x // 10 +x //= 10 while x > 0: if x % 10 > a: a = x % 10 - x = x // 10 + x //= 10 print(a) @@ -52,10 +52,10 @@ # Пример, если число 7089, вывести число 9807. x = int(input()) -a = 0 +a = 0 while x > 0: a = a * 10 + x % 10 - x = x // 10 + x //= 10 print(a) diff --git a/Python/1_home/3.py b/Python/1_home/3.py index 8c9b4eb..16005eb 100644 --- a/Python/1_home/3.py +++ b/Python/1_home/3.py @@ -8,10 +8,11 @@ def checkio(data): if len(data)>9: - if any(i.isupper() for i in data) and any(i.islower() for i in data) and any(i.isdigit() for i in data): - return True - else: - return False + return ( + any(i.isupper() for i in data) + and any(i.islower() for i in data) + and any(i.isdigit() for i in data) + ) else: return False @@ -54,17 +55,13 @@ def checkio(text): # 3 Return a list consisting of only the non-unique elements in this list def checkio(data): - newlst=[] - for i in data: - if data.count(i)>1: - newlst.append(i) - return newlst + return [i for i in data if data.count(i)>1] if __name__ == "__main__": #These "asserts" using only for self-checking and not necessary for auto-testing assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example" - assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example" + assert not list(checkio([1, 2, 3, 4, 5])), "2nd example" assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example" assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example" print("It is all good.") \ No newline at end of file diff --git a/Python/1_home/4.py b/Python/1_home/4.py index d23bf3a..ba17cb5 100644 --- a/Python/1_home/4.py +++ b/Python/1_home/4.py @@ -35,8 +35,7 @@ def length_segment(x1: float, y1: float, x2: float, y2: float): """ Вычисление длины отрезка """ - segment = (((x1 - x2) ** 2) + ((y1 - y2) ** 2)) ** 0.5 - return segment + return (((x1 - x2) ** 2) + ((y1 - y2) ** 2)) ** 0.5 def equation_straight_line(x1: float, y1: float, x2: float, y2: float): @@ -74,13 +73,13 @@ def run(coords=None): if line_a[0] == line_b[0] == line_c[0]: print("a || b || c") - elif (line_a[0] == line_b[0] and (line_a[0] != line_c[0] or line_b[0] != line_c[0])): + elif line_a[0] == line_b[0]: print("a || b") print(0) - elif (line_a[0] == line_c[0] and (line_a[0] != line_b[0] or line_c[0] != line_b[0])): + elif line_a[0] == line_c[0]: print("a || с") print(0) - elif (line_b[0] == line_c[0] and (line_b[0] != line_a[0] or line_c[0] != line_a[0])): + elif line_b[0] == line_c[0]: print("b || с") print(0) else: