Skip to content

Commit b5cfba5

Browse files
committed
fix the comments in the solutions 3, 4, 5, 6, 7, 8, 9;10 quick sort.py is renamed to 10 quick sort recursion.py; refactor the names of the variables, fix russian comments and add english comments in the solution 10
1 parent e50d056 commit b5cfba5

9 files changed

+113
-37
lines changed

03 countdown recursion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def countdown(i):
3535
# Print the number to the screen using the function "print()" and recursively call the function "countdown"
3636
# with the parameter decreased by 1. This is our recursive case.
3737
# When the parameter of the function "countdown" is less than 0,
38-
# then the base case is triggered and the function exits.
38+
# then the base case is triggered and the function stops its work.
3939
else:
4040
print(i)
4141
return countdown(i-1)

04 greeting call stack.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,8 @@ def greet(username):
5656
# Функция "greet" возобновляет свою работу и выводит на экран
5757
# текст "Ok, bye in 3 .. 2 .. 1" при помощи функции "print()".
5858
# ----------
59-
# The function "how_are_you" exits, transfers control to the function "greet" and is removed from the call stack.
59+
# The function "how_are_you" stops its work, transfers control to the function "greet"
60+
# and is removed from the call stack.
6061
# The function "greet" resumes and prints
6162
# the message "Ok, bye in 3 .. 2 .. 1" to the screen using the function "print()".
6263
print("Ok, bye in 3 .. 2 .. 1")
@@ -74,9 +75,9 @@ def greet(username):
7475
# Функция "greet" возобновляет свою работу.
7576
# Функция "greet" завершает свою работу убирается из стека вызовов.
7677
# ----------
77-
# The function "bye" exits, transfers control to the function "greet" and is removed from the call stack.
78+
# The function "bye" stops its work, transfers control to the function "greet" and is removed from the call stack.
7879
# The function "greet" resumes.
79-
# The function "greet" exits and is removed from the call stack.
80+
# The function "greet" stops its work and is removed from the call stack.
8081

8182

8283
# Пытаемся поприветствовать пользователя John Shepard.

05 factorial recursion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def fact(x):
4747
# When a copy of the function "fact" is recursively called with the parameter of 1, then the base case is triggered.
4848
# The copies of the function "fact" in the call stack terminate one by one and return their calculated values
4949
# to the previous recursively called copies of the function "fact"
50-
# until the very first called function "fact" exits.
50+
# until the very first called function "fact" stops its work.
5151
else:
5252
return x * fact(x-1)
5353

06 sum of elements recursion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def sum_of_elem(list_of_elem):
5555
# as a parameter, then the base case is triggered.
5656
# The copies of the function "sum_of_elem" in the call stack terminate one by one and return their calculated values
5757
# to the previous recursively called copies of the function "sum_of_elem"
58-
# until the very first called function "sum_of_elem" exits.
58+
# until the very first called function "sum_of_elem" stops its work.
5959
else:
6060
return list_of_elem[0] + sum_of_elem(list_of_elem[1:])
6161

07 counting elements recursion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def count(list_of_elem):
5656
# as a parameter, then the base case is triggered.
5757
# The copies of the function "count" in the call stack terminate one by one and return their calculated values
5858
# to the previous recursively called copies of the function "count"
59-
# until the very first called function "count" exits.
59+
# until the very first called function "count" stops its work.
6060
else:
6161
return 1 + count(list_of_elem[1:])
6262

08 max element recursion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def find_max_one(list_one):
6363
# as a parameter, then the base case is triggered.
6464
# The copies of the function "find_max_one" in the call stack terminate one by one and return
6565
# their calculated values to the previous recursively called copies of the function "find_max_one"
66-
# until the very first called function "find_max_one" exits.
66+
# until the very first called function "find_max_one" stops its work.
6767
if list_one[0] > list_one[1]:
6868
del list_one[1]
6969
return find_max_one(list_one)

09 binary search recursion.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,8 @@ def binary_search(search_list, low, high, element):
5555
# Переменная "mid" содержит этот индекс среднего элемента.
5656
# Индекс среднего элемента списка "search_list" округляется в меньшую сторону.
5757
# ----------
58-
# if the specified lower bound is less or equal to the specified upper bound
59-
# and this lower bound is greater or equal to 0,
58+
# if the specified lower bound is less than or equal to the specified upper bound
59+
# and this lower bound is greater than or equal to 0,
6060
# then we find the index of the middle element of the list "search_list".
6161
# The variable "mid" stores this index of the middle element.
6262
# The value of the variable "mid" is rounded down.

10 quick sort recursion.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Быстрая сортировка используя рекурсию.
2+
# ----------
3+
# Quick sort using recursion.
4+
5+
6+
# Создаем функцию "quick_sort", которая принимает один входной параметр:
7+
# список "list_to_sort", который содержит числа. Эта функция возвращает отсортированный список по возрастанию.
8+
# ----------
9+
# Create the function "quick_sort" that accepts one parameter: the list "list_to_sort" that contains the numbers.
10+
# This function returns the sorted list in ascending order.
11+
def quick_sort(list_to_sort):
12+
# Создаем базовый случай.
13+
# Базовый случай в рекурсивной функции - это часть кода функции, в которой описывается
14+
# условие прекращения работы функции в целях предотвращения зацикливания.
15+
# Если одна из вызванных рекурсивно копий функции "quick_sort" принимает в качестве параметра список,
16+
# содержащий 1 или 0 элементов, то мы выходим из этой копии функции "quick_sort" и возвращаем этот список
17+
# предыдущей копии функции "quick_sort" в стеке вызовов, поскольку если список содержит 1 или 0 элементов,
18+
# то он уже отсортирован по возрастанию.
19+
# Если изначально вызывается функция "quick_sort", которая принимает в качестве параметра список,
20+
# содержащий 1 или 0 элементов, то функция "quick_sort" сразу возвращает этот список,
21+
# поскольку если список содержит 1 или 0 элементов, то он уже отсортирован по возрастанию.
22+
# Функция "print()" выводит некую указанную информацию на экран или на какое-либо другое устройство вывода.
23+
# ----------
24+
# Create the base case.
25+
# The base case in a recursive function is a part of the function code that describes
26+
# the condition for the termination of the function in order to prevent loops.
27+
# If one of the recursively called copies of the function "quick_sort" takes the list containing 1 or 0 elements
28+
# as a parameter, then we exit this recursively called copy of the function "quick_sort"
29+
# and it returns this list to the previous copy of the function "quick_sort"
30+
# in the call stack, since if a list contains 1 or 0 element, then this list is already sorted in ascending order.
31+
# If the function "quick_sort" is initially called with the list containing 1 or 0 elements as a parameter,
32+
# then the function "quick_sort" immediately returns this list,
33+
# since if a list contains 1 or 0 element, then this list is already sorted in ascending order.
34+
# The function "print()" prints the specified message to the screen, or other standard output device.
35+
if len(list_to_sort) < 2:
36+
return list_to_sort
37+
# Создаем рекурсивный случай.
38+
# Рекурсивный случай в рекурсивной функции - это часть кода функции, в которой функция вызывает сама себя
39+
# в целях выполнения какой-либо задачи.
40+
# Если список "list_to_sort" содержит 2 или больше элементов, то:
41+
# ----------
42+
# Create the recursive case.
43+
# The recursive case in a recursive function is a part of the function code
44+
# in which the function calls itself in order to perform a task.
45+
# If the list "list_to_sort" contains 2 or more elements, then:
46+
else:
47+
# 1. Создается переменная "pivot", которая хранит опорный элемент списка "list_to_sort",
48+
# который равен элементу списка "list_to_sort" под индексом 0.
49+
# ----------
50+
# 1. The variable "pivot", that stores the pivot element of the list "list_to_sort",
51+
# which is equal to the element of the list "list_to_sort" at index 0, is created.
52+
pivot = list_to_sort[0]
53+
# 2. Формируется подсписок элементов списка "list_to_sort",
54+
# которые меньше или равны опорному элементу списка "list_to_sort".
55+
# Для этого мы перебираем все элементы списка "list_to_sort",
56+
# кроме первого элемента этого списка, при помощи цикла for,
57+
# и сохраняем в подсписке "less" только те элементы, которые меньше или равны опорному элементу.
58+
# ----------
59+
# 2. The sublist of the elements of the list "list_to_sort",
60+
# which are less than or equal to the pivot element of the list "list_to_sort", is formed.
61+
# To do this, we iterate over all the elements of the list "list_to_sort",
62+
# except for the first element of this list, using a for loop, and store in the sublist "less"
63+
# only those elements which are less than or equal to the pivot element.
64+
less = [i for i in list_to_sort[1:] if i <= pivot]
65+
# 3. Формируется подсписок элементов списка "list_to_sort",
66+
# которые больше опорного элемента списка "list_to_sort".
67+
# Для этого мы перебираем все элементы списка "list_to_sort",
68+
# кроме первого элемента этого списка, при помощи цикла for,
69+
# и сохраняем в подсписке "greater" только те элементы, которые больше опорного элемента.
70+
# ----------
71+
# 3. The sublist of the elements of the list "list_to_sort",
72+
# which are greater than the pivot element of the list "list_to_sort", is formed.
73+
# To do this, we iterate over all the elements of the list "list_to_sort",
74+
# except for the first element of this list, using a for loop,
75+
# and store in the sublist "greater" only those elements which are greater than the pivot element.
76+
greater = [i for i in list_to_sort[1:] if i > pivot]
77+
# 4. Рекурсивно вызываются копии функции "quick_sort" для подсписков "less" и "greater",
78+
# при этом результаты работ этих рекурсивно вызванных копий функции "quick_sort" конкатенируются
79+
# с опорным элементом (["less" + "pivot" + "greater"]).
80+
# Когда рекурсивно вызывается копия функции "quick_sort", которая принимает в качестве параметра список,
81+
# содержащий 1 или 0 элементов, то срабатывает базовый случай.
82+
# Копии функции "quick_sort" в стеке вызовов поочередно завершают свою работу и
83+
# возвращают свои рассчитанные значения предыдущим рекурсивно вызванным копиям функции "quick_sort" до тех пор,
84+
# пока не завершит работу самая первая вызванная функция "quick_sort".
85+
# ----------
86+
# 4. Copies of the function "quick_sort" are recursively called for the sublists "less" and "greater",
87+
# and the results of these recursively called copies of the function "quick_sort"
88+
# are concatenated to the pivot element (["less" + "pivot" + "greater"]).
89+
# When a copy of the function "quick_sort" is recursively called with the list containing 1 or 0 elements
90+
# as a parameter, then the base case is triggered.
91+
# The copies of the function "quick_sort" in the call stack terminate one by one and return
92+
# their calculated values to the previous recursively called copies of the function "quick_sort"
93+
# until the very first called function "quick_sort" stops its work.
94+
return quick_sort(less) + [pivot] + quick_sort(greater)
95+
96+
97+
# Пытаемся отсортировать список [2, 0, 6, 9, 7, 7] по возрастанию.
98+
# Функция "print()" выводит некую указанную информацию на экран или на какое-либо другое устройство вывода.
99+
# ----------
100+
# Try to sort the list [2, 0, 6, 9, 7, 7] in ascending order.
101+
# The function "print()" prints the specified message to the screen, or other standard output device.
102+
print(quick_sort([2, 0, 6, 9, 7, 7]))

10 quick sort.py

Lines changed: 0 additions & 27 deletions
This file was deleted.

0 commit comments

Comments
 (0)