Article From:https://www.cnblogs.com/ChinacloudTech/p/9970680.html

python Anonymous function and recursive function

Anonymous function

lambdaFunctions are also called anonymous functions, which have no specific name. A sentence function is designed to solve some simple functional requirements. As follows:

#This code
def calc(n):
    return n**n
print(calc(10))
 
#Change to an anonymous function
calc = lambda n:n**n
print(calc(10))

 

 lambda grammar

lambdagrammar

Above is our analysis of calc, an anonymous function. Below is a description of the format of the anonymous function.

 

Function name = lambda parameter: return value

#Parameters can be multiple, separated by commas
#Anonymous functions, no matter how complex the logic is, can only write one line, and the content after the logic execution is the return value.
#The return value can be of any data type as well as a normal function.

As we can see, anonymous functions do not really have names.
Calls to anonymous functions are no different from normal calls. That’s the name of the function (parameter). What’s the advantage of anonymous functions?

1 When using Python to write some execution scripts, lambda can save the process of defining functions and make the code more concise.
2 For some abstract functions that will not be reused elsewhere, sometimes it is a difficult problem to name them. Using lambda does not need to consider naming.
3 Using lambda makes the code easier to understand at some point.

lambdaFunctions are mainly used in conjunction with other functions, such as the following examples:

#We all know that Max (dict) defaults to the maximum value of the key (press ascii).
dic={'k1':10,'k2':100,'k3':30}
print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])

Output:
k3
100

Here’s the source code for max:

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.
    """
    pass

The second example is:

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

Output:
1
25
49
16
64

Map Functional analysis:

PythonThe map function is applied to each iteratable item and returns a result list. If other iterative parameters are passed in, the map function will iterate each parameter with the corresponding processing function. The map () function receives two parameters, one is a function and the other is an order.Column, map, in turn, acts on each element of the sequence with the incoming function, and returns the result as a new list.

A third example

res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)

Output:
11
15

FilterFunctional analysis:

filter()The function receives a function f and a list. The function f judges each element, returns True or False, filter () automatically filters out the unqualified elements based on the judgement result, and returns a new list composed of qualified elements.。

Conclusion:
Anonymous functions are generally used in conjunction with map, max, min, filter, zip functions.

Recursive function

Definition of recursive function: Calling itself in a function. Be careful:The Maximum Depth of Recursion-997
Recursive functions are always executed if they are not blocked by external forces. But we have said before about the problem of function call. Every function call will produce its own namespace. If it is called continuously, it will cause the problem that the namespace occupies too much memory. So pythoN In order to eliminate this phenomenon, the recursive layer is forcibly controlled in 997 (as long as 997! You can’t afford to lose, you can’t afford to be fooled.). What can you prove this “997 theory”? Here we can do an experiment:

def foo(n):
    print(n)
    n += 1
    foo(n)
foo(1)

Output:
1
.
.
.
993
994
995
996
Traceback (most recent call last):
  File "D:/Study/BaiduNetdiskDownload/day15Class Notes / Func. py uuuuuuuuuuuu, line 139, in <module>
    foo(1)
  File "D:/Study/BaiduNetdiskDownload/day15Class Notes / Func. py uuuuuuuuuuuu, line 138, in foo
    foo(n)
  File "D:/Study/BaiduNetdiskDownload/day15Class Notes / Func. py uuuuuuuuuuuu, line 138, in foo
    foo(n)
  File "D:/Study/BaiduNetdiskDownload/day15Class Notes / Func. py uuuuuuuuuuuu, line 138, in foo
    foo(n)
  [Previous line repeated 992 more times]
  File "D:/Study/BaiduNetdiskDownload/day15Class Notes / Func. py uuuuuuuuuuuu, line 136, in foo
    print(n)
RecursionError: maximum recursion depth exceeded while calling a Python object

From this we can see that the maximum number we can see before an error is 997. Of course, 997 is a default value set by Python for memory optimization of our program. Of course, we can also modify it by some means:

import sys
print(sys.setrecursionlimit(100000))

We can modify the maximum depth of recursion in this way. Just now we set the allowable recursion depth of Python to 10w. The actual depth that can be reached depends on the performance of the computer. However, we do not recommend modifying this default recursive depth, because if you use layer 997The problem that recursion hasn’t solved is either that it’s not appropriate to use recursion to solve it or that your code is too bad to write.

Recursive Functions and Binary Search Algorithms

l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
If you look at this list, is it a sequential list sorted from small to large?
If so, if the number I’m looking for is larger than the number in the middle of the list, can I just look for it in the second half of the list?
 Binary Search Idea
Code Realization:
Simple version dichotomy

l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]

def func(l,aim):
    mid = (len(l)-1)//2
    if l:
        if aim > l[mid]:
            func(l[mid+1:],aim)
        elif aim < l[mid]:
            func(l[:mid],aim)
        elif aim == l[mid]:
            print("bingo",mid)
    else:
        print('Can't find ')
func(l,66)
func(l,6)

Upgraded Dichotomy

def search(num,l,start=None,end=None):
    start = start if start else 0
    end = end if end is None else len(l) - 1
    mid = (end - start)//2 + start
    if start > end:
        return None
    elif l[mid] > num :
        return search(num,l,start,mid-1)
    elif l[mid] < num:
        return search(num,l,mid+1,end)
    elif l[mid] == num:
        return mid

Leave a Reply

Your email address will not be published. Required fields are marked *