Level 1: Recursive Functions - The Charm of the Towers of Hanoi
mission details
Inside a Python function, we can call other functions. So if a function calls itself internally, we call this function a recursive function. In this level, we will use the example of the Tower of Hanoi to experience the method and application of recursive functions.
The Tower of Hanoi problem originated from an ancient legend in India. According to legend, when Brahma created the world, he made three diamond pillars, and 64 gold discs were stacked on one pillar in order of size from bottom to top. Brahma ordered the Brahmins to rearrange the discs on another pillar in order of size from below and stipulated that at any time, the discs cannot be enlarged on the small discs, and only one can be moved between the three pillars at a time. disc. As shown in Figure 1 below, how should the operation be done?
figure 1
The goal of this level is to enable learners to understand and master the relevant knowledge of recursive functions through the discussion of the Tower of Hanoi problem.
related information
In a programming language, if each step of a calculation process uses the results of the previous step or steps, the calculation process can be called recursive. A function defined by a recursive calculation process is called a recursive function. Recursive functions are widely used. For example, problems such as continuous addition, continuous multiplication, and factorial can all be solved using recursive thinking. The Tower of Hanoi problem is also a classic application of recursive functions.
The solution to the Tower of Hanoi problem is: if we want to think about how to move each step, it may be very complicated, but the problem can be simplified. We can first assume that except for the bottom plate of the column, the plates above the column a
have been successfully moved to the column. At this time, we only need to move the bottom plate from the column to the column. As shown in Figure 2 below:a
63
b
a
c
figure 2
a
When we move the largest plate from column c
to column, the b
remaining 63
plates are on the column, and a
the column is empty. So now the goal becomes 63
to b
move the plate from column to c
column. This question is exactly the same as the original question, except that the scale is changed from a
column to column . Therefore, the same method can be used, first move the upper plate from column to column, and then move the bottom plate to column.b
64
63
62
b
a
c
By analogy, with the b
aid of the column, move the top discs above a
the column to the column, and move the last disc to the column. We have found the law, we use one of the pillars as an auxiliary every time , and then move the other disks except the bottom disk to the auxiliary pillars, and then move the bottom disk to the pillars , repeating this process continuously.62
61
b
c
a
b
c
This process of repeatedly moving the disc is recursion. For example, every time we want to solve n
the problem of moving a disc, we must first solve (n-1)
the problem of performing the same operation on a disc. Let's assume that a
there is only one disk on the column 3
, and use Python to program to realize the movement of the disk. The code is as follows:
def move(n, a, b, c):
if(n == 1):
print(a,"->",c)
return
move(n-1, a, c, b)
move(1, a, b, c)
move(n-1, b, a, c)
move(3, "a", "b", "c")
Function running result:
a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c
Program analysis:
First, we define a function move(n,a,b,c)
, the parameter n
represents a
the number of disks on the column, a
, b
, c
the order of the three columns represents a
the final movement of the disks on the column to c
the column, and then b
the column is used as the middle column.
We will definitely have a condition to terminate the recursion in a recursive function. The code in lines 2 to 4 means that when a
the number of discs on the column 1
is , the recursion is terminated and returned. Because a
there is only one disc on the column at this time, it must be directly a
moving the disc from column to c
column.
The code in line 5 move(n-1, a, c, b)
indicates that the discs a
on the column must first be moved from column to column, and the column is the middle auxiliary column at this time. The code on line 6 indicates that when the condition is met, move the remaining largest discs on the bar from bar to bar.n-1
a
b
c
move(1, a, b, c)
n=1
a
1
a
c
The code on line 7 move(n-1, b, a, c)
indicates that n-1
the disc has been transferred to the column now, and the function b
is called recursively to move the disc from column to column. At this time, the column is the middle auxiliary column.move
n-1
b
c
a
Finally we call move
the function to move 3
a disc from a
bar to c
bar. When moving 64
a disk, you only need to change move(n,a,b,c)
in the calling function to . This amount of calculation is very huge, and it can only be handed over to the computer to solve it.n
64
summary
We experienced the basic idea of recursive function through the example of Tower of Hanoi, and tried to solve a specific problem. The advantages of recursive functions are clear definition and concise thinking, which can greatly simplify the programming process. Theoretically, all recursive functions can be replaced by circular methods, but the programming process of circular methods is much more complicated than that of recursive functions.
programming requirements
The programming task of this level is to complete src/step1/recursive.py
the code of the file and realize the corresponding functions. Specific requirements are as follows:
- Define a function
fact(n)
that implementsn
operations on input positive integersn!
; - Call the function to perform factorial operation
fact(n)
on the input positive integern
and output the calculation result.
The code framework of the code files involved in this level src/step1/recursive.py
is as follows:
# coding=utf-8
# 输入正整数n
n = int(input())
# 请在此添加代码,对输入的正整数n进行阶乘运算,并输出计算结果。
########## Begin ##########
########## End ##########
Test instruction
The test file of this level is src/step1/recursive.py
, the test process is as follows:
- The platform automatically compiles and generates
recursive.exe
; - The platform runs
recursive.exe
and provides test input as standard input; - The platform takes
recursive.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/step1/recursive.py
a sample test set for a platform pair:
Test input:
5
Expected output:120
Test input:
6
Expected output:
720
Test input:
7
Expected output:
5040
Test input:
8
Expected output:
40320
Let's start your mission, I wish you success!
Although the dream is illusory, it is one's own dream; although the position is low, it is one's post; although the house is simple, it is one's home;
If you think the content of this level is helpful to you, please like it below.
code:
# coding=utf-8
# 输入正整数n
n = int(input())
# 请在此添加代码,对输入的正整数n进行阶乘运算,并输出计算结果。
########## Begin ##########
def move(n):
if n==1:
return 1
else:
return n*move(n-1)
print(move(n))
########## End ##########
Level 2: lambda function - the use of anonymous functions
mission details
In Python programming, in addition to using def
statements to define functions, we can also use lambda
to define. We def
need to specify the function name when we use statements to define functions, but lambda
we don't need to use them to define functions. lambda
Functions are a very unique type of function in Python. The goal of this level is to let learners understand and master lambda
the relevant knowledge of functions.
related information
lambda
Functions are also called anonymous functions. As the name implies, an anonymous function is a function without a name. Maybe we can't accept it now, how can a function work without a name? But actually it can. When we only use some functions temporarily during programming, and the logical functions of these functions are also very simple, there is no need to give these functions a name.
This is similar to the fact that there are many extras in a movie. Each of them has a small role in the scene and only plays the role of temporary performances. Therefore, it is generally not necessary to give extras a movie name, and they can be collectively called group performances.
Anonymous functions do not need return
to return a value, lambda
the result of evaluating the function expression itself is the return value. For example, we can lambda
define an addition as a function that computes the addition of two integers:
f = lambda x,y:x+y
print(f(1,2))
Operation result:
3
x
y
The sum is the two parameters of the function, and :
the following expression x+y
indicates that the function of the function is to calculate the sum of two numbers. Here we did not give the function a name, but directly assigned the anonymous function to the variable f
. Then f
passing in parameters (1,2)
is equivalent to passing in parameters to anonymous functions and getting the returned results 3
.
Although Python is not a purely functional programming language, it provides many functional programming features. Like map
, reduce
, filter
, sorted
these functions all support functions as parameters, and lambda
functions can also be applied in functional programming. For example, now there is a list of integers, and it is required to arrange the elements in the list in ascending order according to the absolute value of the elements in the list. We can def
solve this problem by taking ordinary functions first:
# 给出一个包含正数和负数的列表
list1 = [2,3,-5,0,-4,-8,-1]
# 定义一个函数,返回输入值的绝对值
def f(x):
return abs(x)
# 利用sorted函数对列表中的元素根据绝对值的大小升序排序
list2=sorted(list1, key=f)
# 输出新列表
print(list2)
We can also use lambda
functions to achieve this goal more easily:
# 给出一个包含正数和负数的列表
list1 = [2,3,-5,0,-4,-8,-1]
# 利用sorted函数对列表中的元素根据绝对值的大小升序排序
list2=sorted(list1, key=lambda x: abs(x))
# 输出新列表
print(list2)
As you can see from this example, lambda
functions make some functional programming easier and faster. lambda
Functions can act as shorthand functions, allowing the definition of a function to be embedded within the code being used. In the case where only a small piece of executable code needs to be embedded, it can lead to a more concise code structure.
programming requirements
The programming task of this level is to complete src/step2/lambda.py
the code of the file and realize the corresponding functions. Specific requirements are as follows:
- Use
lambda
to create an anonymous function, then judge the size of the two input values, and output the larger value and the smaller value respectively.
The code framework of the code files involved in this level src/step2/lambda.py
is as follows:
# coding=utf-8
# 请在此添加代码,使用lambda来创建匿名函数,能够判断输入的两个数值的大小,
########## Begin ##########
########## End ##########
# 输入两个正整数
a = int(input())
b = int(input())
# 输出较大的值和较小的值
print('较大的值是:%d' % MAXIMUM(a,b))
print('较小的值是:%d' % MINIMUM(a,b))
Test instruction
The test file of this level is src/step2/lambda.py
, the test process is as follows:
- The platform automatically compiles and generates
lambda.exe
; - The platform runs
lambda.exe
and provides test input as standard input; - The platform takes
lambda.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/step2/lambda.py
a sample test set for a platform pair:
Test input:
5
12
Expected output:
较大的值是:12
较小的值是:5
Test input:
7
3
Expected output:
较大的值是:7
较小的值是:3
Test input:
120
89
Expected output:
较大的值是:120
较小的值是:89
Test input:
13
110
Expected output:
较大的值是:110
较小的值是:13
Let's start your mission, I wish you success!
You can forget failures, but not lessons; you can forget yesterday, but not history; you can forget suffering, but not hardships; you can forget scars, but not disgrace.
If you think the content of this level is helpful to you, please like it below.
code:
# coding=utf-8
# 请在此添加代码,使用lambda来创建匿名函数,能够判断输入的两个数值的大小
########## Begin ##########
MAXIMUM=lambda a,b:max(a,b)
MINIMUM=lambda a,b:min(a,b)
########## End ##########
# 输入两个正整数
a = int(input())
b = int(input())
# 输出较大的值和较小的值
print('较大的值是:%d' % MAXIMUM(a,b))
print('较小的值是:%d' % MINIMUM(a,b))
Level 3: Map-Reduce - The Idea of Mapping and Reduction
mission details
There are two very common built-in functions in Python: map()
the and reduce()
function. These two functions are processing functions applied to sequences, map()
for mapping, and reduce()
for merging. The goal of this level is to let learners understand and master the relevant knowledge of map()
and functions.reduce()
related information
map()
function
map()
The function will map the specified sequence according to the function passed in. map()
A function takes two arguments, one is function
a function and the other is one or more sequences. map()
The function will apply the passed function to each element of the passed sequence in turn, and return the result as a new sequence. map()
The function is defined as:
map(function, sequence[, sequence, ...]) -> list
For example, we want to square each numerical element in a list sequence, combined with lambda
the example of the function mentioned in the previous level, the program code is as follows:
r = map(lambda x: x ** 2, [1, 2, 3, 4,])
print(list(r))
Output result:
[1, 4, 9, 16]
When map()
there are multiple sequences in the second parameter of the function, the elements at the same position in each sequence will be used as parameters in turn and the function
function will be called. For example, to map()
sequentially sum the elements of the two sequences passed in by the function, the program code is as follows:
r = map(lambda x, y: x + y, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
print(list(r))
Output result:
[7, 9, 11, 13, 15]
When map()
there are multiple sequences passed in by the function, we should pay attention to function
the number of parameters of the function, which should map()
match the number of sequences passed in by the function.
reduce()
function
reduce()
The function applies the incoming function to a sequence [x1, x2, x3, ...]
, and this function must receive two parameters. reduce()
The function continues to accumulate the result of the first calculation with the next element in the sequence. reduce()
The function is defined as:
reduce(function, sequence[, initial]) -> value
function
The parameter is a function with two parameters. reduce()
The function takes elements in the sequence in turn, and function
uses the result of the last function call as a parameter, and then calls function
the function again. For example:
from functools import reduce
r = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5],6)
print(r)
Output result:
21
In the above example, the order of computation of the program is ((((((1+6)+2)+3)+4)+5))
.
summary
map()
The application of sum reduce()
function is very extensive, and it has a very important application in the field of distributed computing. We look forward to learners having a deeper experience with map()
and functions in the future development path .reduce()
programming requirements
The programming task of this level is to complete src/step3/map-reduce.py
the code of the file and realize the corresponding functions. Specific requirements are as follows:
- Decompose a positive integer input into prime factors and output the result. For example: input
90
, print out90=2*3*3*5*
.
The code framework of the code files involved in this level src/step3/map-reduce.py
is as follows:
# coding=utf-8
# 输入一个正整数
x = int(input())
# 请在此添加代码,将输入的一个正整数分解质因数
########## Begin ##########
########## End ##########
# 输出结果,利用map()函数将结果按照规定格式输出
print(x,'=','*'.join(map(str,result)))
Test instruction
The test file of this level is src/step3/map-reduce.py
, the test process is as follows:
- The platform automatically compiles and generates
map-reduce.exe
; - The platform runs
map-reduce.exe
and provides test input as standard input; - The platform takes
map-reduce.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/step3/map-reduce.py
a sample test set for a platform pair:
Test input:
80
Expected output:
80 = 2*2*2*2*5
Test input:
79
Expected output:
79 = 79
Test input:
225
Expected output:
225 = 3*3*5*5
Test input:
123456
Expected output:
123456 = 2*2*2*2*2*2*3*643
Let's start your mission, I wish you success!
If you think the content of this level is helpful to you, please like it below.
code:
# coding=utf-8
# 输入一个正整数
x = int(input())
# 请在此添加代码,将输入的一个正整数分解质因数
########## Begin ##########
result=[]
m=x
j=0
for n in range(2,m):
while(m%n==0):
j+=1
m=m/n
result.append(n)
if(j==0):
result.append(m)
########## End ##########
# 输出结果,利用map()函数将结果按照规定字符串格式输出
print(x,'=','*'.join(map(str,result)))