Python--recursive functions and anonymous functions (lambda expressions)

1. Recursive function

如果一个函数在内部不调用其他的函数,
而是调用自身的话,这个函数就是递归函数。

1.1 Characteristics of recursive functions

Insert picture description here
Example: Use a recursive function to calculate 5!

# 应用: 运用递归函数计算5!
def fn(num):
    if num == 1:
        result = 1
    else:
        result = fn(num - 1) * num
    return result


n = int(input("请输入一个正整数: "))
print(str(n) + " 的阶乘是: " + str(fn(n)))

Operation result:
Insert picture description here
the process of function call:
Insert picture description here


Anonymous function

匿名函数(lambda)是指没有名字的函数,即不再使用def语句定义的函数。
可以运用在需要一个函数但是又不想费神去命名这个函数的场合中。
通常情况下,这样的函数只使用一次。

Insert picture description here
Parameter Description:

  • result: the return value of the function
  • [arg1 [,arg2,..., argn]]: optional parameters, used to specify the list of parameters to be passed, multiple parameters are separated by commas.
  • expression: Required parameter, used to specify an expression to achieve a specific function. If there are parameters, they will be applied in the expression.
  • When using lambda expressions, there can be multiple parameters, but the expression can only have one, that is, only one value can be returned, and no other non-expression statements can appear. Such as (for or while).

Example:

add = lambda arg1, arg2: arg1 + arg2

# 调用sum函数
print(add(1, 2))

operation result:
Insert picture description here

Insert picture description here


1.1 Advanced use of anonymous functions

我们可以将匿名函数作为参数传递。

Example:

def fun(a, b, opt):
    print("a = %d" % a)
    print("b = %d" % b)
    print("result = ", opt(a, b))


fun(1, 2, lambda x, y: x + y)

operation result:
Insert picture description here

匿名函数作为内置函数的参数来使用
stus = [
    {
    
    "name": "小樱", "age": 18},
    {
    
    "name": "小红", "age": 17},
    {
    
    "name": "小绿", "age": 19},
]
# 按age排序:
stus.sort(key=lambda x: x['age'])
print(stus)

operation result:
Insert picture description here


Comprehensive example: recursive function

# 5.打印斐波那契数列 1 1 2 3 5 8 13....打印36项,每行打印6个
Fibonacci_num = 36


def getSum(num):
    if num == 1 or num == 2:
        return 1
    else:
        return getSum(num - 1) + getSum(num - 2)


format_flag = 0
for item in range(1, 37):
    print(getSum(item), end="\t\t")
    format_flag += 1
    if format_flag % 6 == 0:
        print()

operation result:
Insert picture description here


Guess you like

Origin blog.csdn.net/I_r_o_n_M_a_n/article/details/115328154