In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to call Python recursive functions and anonymous functions". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to call Python recursive functions and anonymous functions".
one。 Recursive function
A) introduction: what happens if you call yourself in a function? Will fall into an infinite call loop. To solve this problem, you need to use recursion.
B) Application:
i. Case study: write a function that receives an integer n and then calculates the factorial of the output n.
1. First define a function def factorial (n). How should this function be implemented? We know that there is a law for calculating the factorial of n as follows: [(n Mel 1) * [n Mel 2]... * 1] = n * (nmur1)!
two。 The steps to implement the function can be:
Def factorial (n):
1. Calculate the factorial of (nmur1)
two。 Returns the result value of step1 * n
To complete the first step is to calculate (nmur1). Since our function is to calculate the factorial, the first step can also be understood as calling the function with the argument of nmur1. The code becomes:
Def factorial (n):
1.factorial (nmur1)
two。 Returns the result value of step1 * n
In this code, there is a call to the factorial function in the factorial function. There is a recursion of the function. To improve the above code, the second part of the code can also be translated into code:
Def factorial (n):
1. Int result=factorial (nMui 1)
2. Return result*n
But the problem also arises. If you add nasty 3, fac (2) will be called inside fac (3), fac (1) will be called in fac (2), fac (0)-"fac (- 1) will be called in fac (1). So we need to specify a condition for the end of the loop call. In the current program, when the value of parameter n is 1, the factorial of 1 is calculated, so there is no need to continue recursion at this step, so nforth 1 is and should be returned directly.
Def factorial (n):
If (naughty 1):
Return 1
Int result=factorial (nmur1)
Return result*n
two。 Anonymous function
A) introduction: when we create a function, sometimes we do not need to display the definition function, it will be more convenient to pass in the anonymous function directly, which will save us the trouble of naming the function and a lot less code. Many programming languages provide anonymous functions. If the anonymous function is well used, it will play the finishing touch. if it is not used well, it will be easy to draw a tiger and not an anti-dog.
B) use the lambda keyword in Python to create anonymous functions. The so-called anonymity means that functions are no longer defined in the standard form of def. Note that:
I. lambda is an expression, not a block of code
ii. Only limited logic can be encapsulated in lambda expressions
iii. The Lambda function has its own namespace
C) Syntax structure: lambda parameter: expression such as lambda x:x*x, the x before the colon represents the parameter, and the following represents the execution code of the function, which is equivalent to the following function:
Def f (x): return Xerox
D) Note:
i. Anonymous functions can have only one expression
ii. Do not use and cannot write return statements, the result of the expression is the return value
iii. An anonymous function is also a function object that can be assigned to a variable and then called through the variable. F=lambda x:x*x f (6)
three。 Deductive: it is a unique deductive syntax that can help us write concise and cool code on some occasions. But without it, it won't have much impact.
A) Classification:
i. List derivation
ii. Dictionary derivation
iii. Set derivation
iv. Tuple derivation?
B) list derivation: a way to quickly generate a list in the form of a statement enclosed in square brackets.
i. Case study: lis= [xquox for x in range (1Power10)] first executes the for loop, and for each x brought into xquox, the result value of the operation is added to a new list one by one (the variable used in the formula of xquox must be x in for). In particular, list deduction provides us with a way to generate lists that implement more complex logic in one line. The core syntax is to encapsulate the generated logic in square brackets.
ii. Case: [Xerox for x in range (1Magne11) if x% 2filtering 0] filter x by adding if statements
iii. Case: dic= {"K1": "v1", "K2": "v2"} a = [k + ":" + v for kprit v in dic.items ()]
C) Dictionary derivation: list deduction uses square braces, so you can create dictionary deduction if you use curly braces
i. Case: dic= {x:x*2 for x in (2pr 4J 6)} the colon in the middle of the x:x*2 indicates key on the left and value on the right.
ii. Case: you can also add an if clause
D) set derivation: curly braces can be used not only as a dictionary derivation but also as a collection derivation. Note the difference between the two.
i. Case: a = {x for x in "abcdefg" if x not in "abc"}
E) tuple derivation: is that in parentheses? is it no? The syntax called generator, which uses parentheses in python, has no tuple deduction in python.
i. If you want to generate tuples through a similar method described above, you need to display the type conversion function tuple that calls the tuple. T=tuple (x for x in range (10))
F) interview questions:
Result = [lambda x: X + i for i in range (10)]
Print (result [0] (10))
The answer is 19, and the result of result [0,9] (10) is 19. This is because the function has the property of finding variables when called. It does not save or care about the specific values of its internal variables until you call it. Only when you call it will it look for the specific values of these variables one by one. When result [0] is called here, the variable I has been looped and changed to 9 instead of the dynamic 0-9 value imagined.
What if you don't want this result and you want I to be the value of a loop? Do not directly refer to the upper variable, pass the variable directly in.
Result = [lambda x, iTuni: X + i for i in range (10)]
Print (result [0] (10))
four。 Iterator
A) iteration: the process of iterating through each element of an object through a for loop. For can traverse any object that can be iterated over.
B) iterable object type: list/tuple/string/dict/set/bytes. You can determine whether an object can be iterated by the Iterable type of the collections module:
From collections import Iterable
Whether isinstance ('abc', Iterable) # str is iterative
C) iterator: an object that can be traversed. The features are as follows:
i. You can call the next () function.
ii. Create an iterator object using the iter () function
iii. The iterator object is accessed from the first element of the collection until all elements are accessed
iv. You can only traverse backwards, not backwards.
v. Case study:
> lis= [1, 2, 3, 4]
> it = iter (lis) # create an iterator object using Python's built-in iter () method
> next (it) # use the next () method to get the next element of the iterator
one
> next (it)
two
> next (it)
three
> next (it)
four
> next (it) # pops up an error when there is no element to next
Or use the for loop to iterate through the iterator:
Lis = [1, 2, 3, 4]
It = iter (lis) # create an iterator object
For x in it: # iterate through objects using for loops
Print (x, end= "")
The role of iterators: in addition to iterable types can be iterated, in the development will also encounter some custom types also have iterative requirements, that is, custom types can be defined as iterator types (you need to implement _ _ iter__ () and _ _ next__ () methods in the class, which can be called by next and iter functions). The for loop is essentially implemented by constantly calling the next () function.
Def iter (obj):
Return obj.__iter__ ()
Def next (obj):
Return obj.__next__ ()
Custom iterator class:
Import random
Class demo_iterator (object):
Def _ next__ (self):
V = random.randint (0pc10)
If v
< 5: raise StopIteration() else: return v def __iter__(self): return demo_iterator() 迭代作用:可以把这个元素流看做是一个有序序列,但却不能提前知道序列的长度,只能不断通过next()函数得到下一个元素,所以迭代器可以节省内存和空间。 五. 生成器 a) 引言:有时候,序列或集合内的元素的个数非常巨大,如果全制造出来并放入内存,对计算机的压力是非常大的。比如,假设需要获取一个10**20次方如此巨大的数据序列,把每一个数都生成出来,并放在一个内存的列表内,这是粗暴的方式,有如此大的内存么?如果元素可以按照某种算法推算出来,需要就计算到哪个,就可以在循环的过程中不断推算出后续的元素,而不必创建完整的元素集合,从而节省大量的空间。在Python中,这种一边循环一边计算出元素的机制,称为生成器:generator。 b) 语法格式:类似推导式,使用小括号 c) 案例: >> > g = (x * x for x in range (1,4))
> > g
At 0x1022ef630 >
You can get the next return value of generator through the next () function, which is very similar to an iterator:
> > next (g)
one
But more often, we use for loops.
For i in g:
Print (I)
D) keyword yield:
1. Usage: the function returned by using yield becomes a generator. During the call to the generator, every time a yield is encountered, the function pauses and saves all the current running information and returns the value of yeild. And continue execution from the current location the next time you run the next method.
Thank you for reading, the above is the content of "how to call Python recursive functions and anonymous functions". After the study of this article, I believe you have a deeper understanding of how to call Python recursive functions and anonymous functions, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.