Skip to content

Commit fbe8c8c

Browse files
committed
fix the comments in the solution 5; fix russian comments and add english comments in the solution 6
1 parent 7c5cc9f commit fbe8c8c

File tree

2 files changed

+66
-13
lines changed

2 files changed

+66
-13
lines changed

05 factorial recursion.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def fact(x):
2424
# If one of the recursively called copies of the function "fact" calculates the factorial of the number 1,
2525
# then we exit this recursively called copy of the function "fact" and it returns the number "1" to
2626
# the previous copy of the function "fact" in the call stack.
27-
# If the function "fact" is initially called with a parameter of 1,
27+
# If the function "fact" is initially called with the parameter of 1,
2828
# then the function "fact" immediately returns the number 1, since the factorial of the number 1 is 1.
2929
# The keyword "return" is to exit a function and return a value.
3030
if x == 1:
@@ -44,7 +44,7 @@ def fact(x):
4444
# in which the function calls itself in order to perform a task.
4545
# Recursively call a copy of the function "fact" with the parameter decreased by 1,
4646
# the result of which is multiplied by the value of the parameter of the current copy of the function "fact".
47-
# When a copy of the function "fact" is recursively called with a parameter of 1, then the base case is triggered.
47+
# 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"
5050
# until the very first called function "fact" exits.

06 sum of elements recursion.py

Lines changed: 64 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,68 @@
1-
# Создаем функцию для подсчета суммы всех элементов списка при помощи рекурсии.
2-
def sum(list):
3-
# Определяем базовый случай как если список не содержит элементов, то сумма его элементов равна 0.
4-
if len(list) == 0:
5-
return 0
1+
# Сумма элементов используя рекурсию.
2+
# ----------
3+
# Sum of elements using recursion.
4+
65

7-
# Определяем рекурсивный случай,
8-
# чтобы при помощи него приблизиться к нашему базовому случаю для выхода из рекурсии и получения итогового ответа.
9-
# В рекурсии мы вызываем функцию со списком без первого элемента до тех, пор пока в массиве не останется элементов,
10-
# чтобы попасть в базовый случай.
6+
# Создаем функцию "sum_of_elem", которая принимает один входной параметр:
7+
# список "list_of_elem", содержащий элементы, сумму которых необходимо вычислить.
8+
# ----------
9+
# Create the function "sum_of_elem" that accepts one parameter:
10+
# the list "list_of_elem" containing the elements to be summed.
11+
def sum_of_elem(list_of_elem):
12+
# Создаем базовый случай.
13+
# Базовый случай в рекурсивной функции - это часть кода функции, в которой описывается
14+
# условие прекращения работы функции в целях предотвращения зацикливания.
15+
# Если одна из вызванных рекурсивно копий функции "sum_of_elem" принимает в качестве параметра список,
16+
# содержащий 0 элементов, то мы выходим из этой копии функции и возвращаем число "0"
17+
# предыдущей копии функции "sum_of_elem" в стеке вызовов, поскольку сумма 0 элементов всегда равна 0.
18+
# Если изначально вызывается функция "sum_of_elem", которая принимает в качестве параметра список,
19+
# содержащий 0 элементов, то функция "sum_of_elem" сразу возвращает число "0", поскольку сумма 0 элементов
20+
# всегда равна 0.
21+
# Ключевое слово "return" выходит из функции и возвращает какое-либо значение.
22+
# ----------
23+
# Create the base case.
24+
# The base case in a recursive function is a part of the function code that describes
25+
# the condition for the termination of the function in order to prevent loops.
26+
# If one of the recursively called copies of the function "sum_of_elem" takes the list containing 0 elements
27+
# as a parameter, then we exit this recursively called copy of the function "sum_of_elem"
28+
# and it returns the number "0" to the previous copy of the function "sum_of_elem" in the call stack,
29+
# since the sum of 0 elements is always 0.
30+
# If the function "sum_of_elem" is initially called with the list containing 0 elements as a parameter,
31+
# then the function "sum_of_elem" immediately returns the number "0", since the sum of 0 elements is always 0.
32+
# The keyword "return" is to exit a function and return a value.
33+
if len(list_of_elem) == 0:
34+
return 0
35+
# Создаем рекурсивный случай.
36+
# Рекурсивный случай в рекурсивной функции - это часть кода функции, в которой функция вызывает сама себя
37+
# в целях выполнения какой-либо задачи.
38+
# Рекурсивно вызываем копию функции "sum_of_elem" со списком "list_of_elem" в качестве входного параметра,
39+
# за исключением первого элемента в этом списке, при этом результат работы этой рекурсивно вызванной копии
40+
# функции "sum_of_elem" суммируется с первым элементом входного параметра текущей копии функции "list_of_elem".
41+
# Когда рекурсивно вызывается копия функции "sum_of_elem", которая принимает в качестве параметра список,
42+
# содержащий 0 элементов, то срабатывает базовый случай.
43+
# Копии функции "sum_of_elem" в стеке вызовов поочередно завершают свою работу
44+
# и возвращают свои рассчитанные значения предыдущим рекурсивно вызванным копиям функции "sum_of_elem" до тех пор,
45+
# пока не завершит работу самая первая вызванная функция "sum_of_elem".
46+
# ----------
47+
# Create the recursive case.
48+
# The recursive case in a recursive function is a part of the function code
49+
# in which the function calls itself in order to perform a task.
50+
# Recursively call a copy of the function "sum_of_elem" with the list "list_of_elem" as a parameter,
51+
# except for the first element of this list, while the result of
52+
# this recursively called copy of the function "sum_of_elem" is summed up with the first element of the parameter
53+
# of the current copy of the function "sum_of_elem".
54+
# When a copy of the function "sum_of_elem" is recursively called with the list containing 0 elements
55+
# as a parameter, then the base case is triggered.
56+
# The copies of the function "sum_of_elem" in the call stack terminate one by one and return their calculated values
57+
# to the previous recursively called copies of the function "sum_of_elem"
58+
# until the very first called function "sum_of_elem" exits.
1159
else:
12-
return list[0] + sum(list[1:])
60+
return list_of_elem[0] + sum_of_elem(list_of_elem[1:])
1361

1462

15-
print(sum([1, 2, 3]))
63+
# Попытаемся найти сумму 13, 7, 37, 7 и 5.
64+
# Функция "print()" выводит некую указанную информацию на экран или на какое-либо другое устройство вывода.
65+
# ----------
66+
# Try to find the sum of 13, 7, 37, 7 and 5.
67+
# The function "print()" prints the specified message to the screen, or other standard output device.
68+
print(sum_of_elem([13, 7, 37, 7, 5]))

0 commit comments

Comments
 (0)