Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions Python/0_algorithms/hw_1/08_leap_year.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("Високосный")
print("Обычный")
2 changes: 1 addition & 1 deletion Python/0_algorithms/hw_2/02_even_odd.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
even += 1
else:
odd += 1
num = num // 10
num //= 10

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 17-17 refactored with the following changes:

  • Replace assignment with augmented assignment (aug-assign)

print(f"четных - {even}, нечетных - {odd}")


Expand Down
2 changes: 1 addition & 1 deletion Python/0_algorithms/hw_2/03_revers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
result = 0
while num > 0:
result = result * 10 + num % 10
num = num // 10
num //= 10

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 14-14 refactored with the following changes:

  • Replace assignment with augmented assignment (aug-assign)

print(result)

# вариант 2
Expand Down
5 changes: 1 addition & 4 deletions Python/0_algorithms/hw_2/07_teorema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sum_natural refactored with the following changes:



n = int(input('Введите любое натуральное число: '))
Expand Down
4 changes: 1 addition & 3 deletions Python/0_algorithms/hw_2/09_max_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function sum_digits refactored with the following changes:



num = int(input('Введите натуральное число. Ноль - выйти '))
Expand Down
5 changes: 1 addition & 4 deletions Python/0_algorithms/hw_3/01_99_div_2-9.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 10-13 refactored with the following changes:

print(f'Числу {i} кратно {frequency} чисел')

# вариант 2
Expand Down
5 changes: 1 addition & 4 deletions Python/0_algorithms/hw_3/02_even_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 14-17 refactored with the following changes:

print(f'Индексы чётных элементов: {result}')

result_new = [i for i in range(len(array)) if array[i] % 2 == 0]
Expand Down
5 changes: 1 addition & 4 deletions Python/0_algorithms/hw_3/04_max_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 14-17 refactored with the following changes:

if spam > frequency:
frequency = spam
num = array[i]
Expand Down
6 changes: 1 addition & 5 deletions Python/0_algorithms/hw_3/05_max_below_zero.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Comment on lines -12 to -21

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 12-21 refactored with the following changes:

This removes the following comments ( why? ):

# вариант 1

if index != -100500:
print(f'Максимальное отрицательное число {array[index]} '
f'находится в ячейке {index}')
Expand Down
4 changes: 1 addition & 3 deletions Python/0_algorithms/hw_3/06_sum_betwen_min_max.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 26-28 refactored with the following changes:

print(f'Сумма = {summ}')
6 changes: 3 additions & 3 deletions Python/0_algorithms/hw_3/09_max_in_mins.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Comment on lines -19 to +21

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 19-21 refactored with the following changes:


if max_ is None or max_ < min_:
max_ = min_
Expand Down
18 changes: 7 additions & 11 deletions Python/0_algorithms/hw_4/1_counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,31 @@


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
Comment on lines -5 to -12

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 5-33 refactored with the following changes:

print()

fab = collections.Counter(d)

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)
Expand Down
2 changes: 1 addition & 1 deletion Python/0_algorithms/hw_4/1_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-15 refactored with the following changes:

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]))

Expand Down
6 changes: 2 additions & 4 deletions Python/0_algorithms/hw_4/1_namedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 7-18 refactored with the following changes:

company = companies(name=input("Введите название предприятия: "),
period_1=int(input("Введите прибыль за первый квартал: ")),
period_2=int(input("Введите прибыль за второй квартал: ")),
Expand All @@ -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():
Expand Down
4 changes: 2 additions & 2 deletions Python/0_algorithms/hw_4/2_defaultdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Comment on lines -18 to +21

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 18-21 refactored with the following changes:

print("Сумма: ", list('%X' % sum))

mult = functools.reduce(lambda a, b: a * b, [int(''.join(i), 16) for i in nums.values()])
Expand Down
8 changes: 4 additions & 4 deletions Python/0_algorithms/hw_4/2_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Comment on lines -16 to +17

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function hex_sum refactored with the following changes:

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))
Comment on lines -24 to +25

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function hex_mul refactored with the following changes:

s = hex((int(float.fromhex(x) * float.fromhex(y))))
s = deque(s[2::].upper())
print("Произведение:", s)
Expand Down
15 changes: 7 additions & 8 deletions Python/0_algorithms/hw_4/2_namedtuple_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines -29 to +35

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function HexCalc.to_hex refactored with the following changes:



a = input("Введите перове число в шестнадцатиричном формате: ").upper()
Expand Down
2 changes: 1 addition & 1 deletion Python/0_algorithms/hw_4/2_ordereddict_deque.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function hex_to_decimal refactored with the following changes:



def decimal_to_hex(num):
Expand Down
5 changes: 2 additions & 3 deletions Python/0_algorithms/hw_4/t_sieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Comment on lines -21 to +25

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function prime refactored with the following changes:


array[1] = 0
for i in range(2, size):
Expand Down
6 changes: 2 additions & 4 deletions Python/0_algorithms/hw_5/2_loop_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Comment on lines -7 to +9

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 7-11 refactored with the following changes:

all_comp.append(Comp(name, *spam, sum(spam)))

print(all_comp)
Expand Down
4 changes: 2 additions & 2 deletions Python/0_algorithms/hw_6/02_even_odd.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
even += 1
else:
odd += 1
num = num // 10
num //= 10

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-32 refactored with the following changes:

  • Replace assignment with augmented assignment [×2] (aug-assign)


print(sys.getsizeof(even))
print(sys.getsizeof(odd))
Expand All @@ -29,7 +29,7 @@
even += 1
else:
odd += 1
num = num // 10
num //= 10

sum_ += sys.getsizeof(even)
sum_ += sys.getsizeof(odd)
Expand Down
2 changes: 1 addition & 1 deletion Python/0_algorithms/hw_6/_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 40-40 refactored with the following changes:


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))
Expand Down
Loading