Experiment 1 Classic Function Example

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 ahave 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:a63bac


figure 2

aWhen we move the largest plate from column cto column, the bremaining 63plates are on the column, and athe column is empty. So now the goal becomes 63to bmove the plate from column to ccolumn. This question is exactly the same as the original question, except that the scale is changed from acolumn 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.b646362bac

By analogy, with the baid of the column, move the top discs above athe 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.6261bcabc

This process of repeatedly moving the disc is recursion. For example, every time we want to solve nthe 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 athere 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:

  1. def move(n, a, b, c):
  2. if(n == 1):
  3. print(a,"->",c)
  4. return
  5. move(n-1, a, c, b)
  6. move(1, a, b, c)
  7. move(n-1, b, a, c)
  8. move(3, "a", "b", "c")

Function running result:

  1. a -> c
  2. a -> b
  3. c -> b
  4. a -> c
  5. b -> a
  6. b -> c
  7. a -> c

Program analysis:

First, we define a function move(n,a,b,c), the parameter nrepresents athe number of disks on the column, a, b, cthe order of the three columns represents athe final movement of the disks on the column to cthe column, and then bthe 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 athe number of discs on the column 1is , the recursion is terminated and returned. Because athere is only one disc on the column at this time, it must be directly amoving the disc from column to ccolumn.

The code in line 5 move(n-1, a, c, b)indicates that the discs aon 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-1abcmove(1, a, b, c)n=1a1ac

The code on line 7 move(n-1, b, a, c)indicates that n-1the disc has been transferred to the column now, and the function bis called recursively to move the disc from column to column. At this time, the column is the middle auxiliary column.moven-1bca

Finally we call movethe function to move 3a disc from abar to cbar. When moving 64a 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.n64

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.pythe code of the file and realize the corresponding functions. Specific requirements are as follows:

  • Define a function fact(n)that implements noperations on input positive integers n!;
  • Call the function to perform factorial operation fact(n)on the input positive integer nand output the calculation result.

The code framework of the code files involved in this level src/step1/recursive.pyis as follows:

  1. # coding=utf-8
  2. # 输入正整数n
  3. n = int(input())
  4. # 请在此添加代码,对输入的正整数n进行阶乘运算,并输出计算结果。
  5. ########## Begin ##########
  6. ########## End ##########

Test instruction

The test file of this level is src/step1/recursive.py, the test process is as follows:

  1. The platform automatically compiles and generates recursive.exe;
  2. The platform runs recursive.exeand provides test input as standard input;
  3. The platform takes recursive.exethe 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.pya sample test set for a platform pair:

Test input:

  1. 5

Expected output:120

Test input:

  1. 6

Expected output:

  1. 720

Test input:

  1. 7

Expected output:

  1. 5040

Test input:

  1. 8

Expected output:

  1. 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 defstatements to define functions, we can also use lambdato define. We defneed to specify the function name when we use statements to define functions, but lambdawe don't need to use them to define functions. lambdaFunctions are a very unique type of function in Python. The goal of this level is to let learners understand and master lambdathe relevant knowledge of functions.

related information

lambdaFunctions 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 returnto return a value, lambdathe result of evaluating the function expression itself is the return value. For example, we can lambdadefine an addition as a function that computes the addition of two integers:

  1. f = lambda x,y:x+y
  2. print(f(1,2))

Operation result:

  1. 3

xyThe sum is the two parameters of the function, and :the following expression x+yindicates 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 fpassing 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, sortedthese functions all support functions as parameters, and lambdafunctions 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 defsolve this problem by taking ordinary functions first:

  1. # 给出一个包含正数和负数的列表
  2. list1 = [2,3,-5,0,-4,-8,-1]
  3. # 定义一个函数,返回输入值的绝对值
  4. def f(x):
  5. return abs(x)
  6. # 利用sorted函数对列表中的元素根据绝对值的大小升序排序
  7. list2=sorted(list1, key=f)
  8. # 输出新列表
  9. print(list2)

We can also use lambdafunctions to achieve this goal more easily:

  1. # 给出一个包含正数和负数的列表
  2. list1 = [2,3,-5,0,-4,-8,-1]
  3. # 利用sorted函数对列表中的元素根据绝对值的大小升序排序
  4. list2=sorted(list1, key=lambda x: abs(x))
  5. # 输出新列表
  6. print(list2)

As you can see from this example, lambdafunctions make some functional programming easier and faster. lambdaFunctions 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.pythe code of the file and realize the corresponding functions. Specific requirements are as follows:

  • Use lambdato 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.pyis as follows:

  1. # coding=utf-8
  2. # 请在此添加代码,使用lambda来创建匿名函数,能够判断输入的两个数值的大小,
  3. ########## Begin ##########
  4. ########## End ##########
  5. # 输入两个正整数
  6. a = int(input())
  7. b = int(input())
  8. # 输出较大的值和较小的值
  9. print('较大的值是:%d' % MAXIMUM(a,b))
  10. print('较小的值是:%d' % MINIMUM(a,b))

Test instruction

The test file of this level is src/step2/lambda.py, the test process is as follows:

  1. The platform automatically compiles and generates lambda.exe;
  2. The platform runs lambda.exeand provides test input as standard input;
  3. The platform takes lambda.exethe 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.pya sample test set for a platform pair:

Test input:

  1. 5
  2. 12

Expected output:

  1. 较大的值是:12
  2. 较小的值是:5

Test input:

  1. 7
  2. 3

Expected output:

  1. 较大的值是:7
  2. 较小的值是:3

Test input:

  1. 120
  2. 89

Expected output:

  1. 较大的值是:120
  2. 较小的值是:89

Test input:

  1. 13
  2. 110

Expected output:

  1. 较大的值是:110
  2. 较小的值是: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 functiona 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:

  1. map(function, sequence[, sequence, ...]) -> list

For example, we want to square each numerical element in a list sequence, combined with lambdathe example of the function mentioned in the previous level, the program code is as follows:

  1. r = map(lambda x: x ** 2, [1, 2, 3, 4,])
  2. print(list(r))

Output result:

  1. [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 functionfunction 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:

  1. r = map(lambda x, y: x + y, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
  2. print(list(r))

Output result:

  1. [7, 9, 11, 13, 15]

When map()there are multiple sequences passed in by the function, we should pay attention to functionthe 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:

  1. reduce(function, sequence[, initial]) -> value

functionThe parameter is a function with two parameters. reduce()The function takes elements in the sequence in turn, and functionuses the result of the last function call as a parameter, and then calls functionthe function again. For example:

  1. from functools import reduce
  2. r = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5],6)
  3. print(r)

Output result:

  1. 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.pythe 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 out 90=2*3*3*5*.

The code framework of the code files involved in this level src/step3/map-reduce.pyis as follows:

  1. # coding=utf-8
  2. # 输入一个正整数
  3. x = int(input())
  4. # 请在此添加代码,将输入的一个正整数分解质因数
  5. ########## Begin ##########
  6. ########## End ##########
  7. # 输出结果,利用map()函数将结果按照规定格式输出
  8. 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:

  1. The platform automatically compiles and generates map-reduce.exe;
  2. The platform runs map-reduce.exeand provides test input as standard input;
  3. The platform takes map-reduce.exethe 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.pya sample test set for a platform pair:

Test input:

  1. 80

Expected output:

  1. 80 = 2*2*2*2*5

Test input:

  1. 79

Expected output:

  1. 79 = 79

Test input:

  1. 225

Expected output:

  1. 225 = 3*3*5*5

Test input:

  1. 123456

Expected output:

  1. 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)))
 

Guess you like

Origin blog.csdn.net/weixin_62174595/article/details/127179497