This paper selects the 10 questions that have been liked most on StackOverflow, the world's second largest gay dating website, of which the total number of likes exceeds 50000. Considering many white whoring parties, at least 100000 people are interested in these questions!
So many people like it, which shows two problems:
1. These problems are very common and often encountered during programming
2. These questions are not simple, otherwise you don't have to go to the forum
10 questions. How many do you know?
- What is the key word of Yield?
- What does ifname== 'main' do?
- Does Python have ternary operators?
- What does Python's metaclasses do?
- If there is no exception, check whether the file exists?
- How to combine two dictionaries in one sentence?
- How does Python call external commands, such as starting QQ?
- How to create a multi-layer folder safely?
- How do I access subscripts in a loop?
- What is the difference between staticmethod and classmethod?
Some of these 10 questions are complex and some are simple. How many do you know? You can leave a message in the comment area.
I originally intended to explain 10 questions, but due to space reasons, this article only covers the most asked question, and subsequent articles may cover multiple questions.
Let's focus on the first question:
What does yield keyword do?
This question ranks first among all Python questions:
- 1. More than 10000 people praised the problem and expressed the same doubts.
- 2. Gao Zan answered more than 15000 likes.
- 3. There are more than 2.4 million views.
Question details?
What is the key word of Yield?
For example, the following code:
def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_dist >= self._median: yield self._rightchild
This is the calling code:
result, candidates = [], [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance <= max_dist and distance >= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result
When_ get_ child_ What happens when candidates is called? Returned a list? Or an element? Will it be adjusted repeatedly? When will subsequent calls stop?
Look a little confused? You can continue to look at the solution, and then come back to the problem.
Highest praise answer (more than 15000 praise)
To understand yield, first understand generators. To understand generators, first understand iteratable.
Iterables
When you create a list, you can read its values one by one. This is called iteration:
>>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i) 1 2 3
The mylist above is an iteratable. When you create a list, you use the formula itemable:
>>> mylist = [x*x for x in range(3)] >>> for i in mylist: ... print(i) 0 1 4
So you can use the for... in... Syntax to traverse iterable: list, str, file, etc
These iterable are very useful. You can cycle through them. But all their values are stored in memory. If there are 1 billion strings in your list, creating this list will be very slow and will take up a lot of memory, so we need Genertor
Generators
The Generator is iterable and can be cycled. But unlike the above, it can only be cycled once. It doesn't store all the values in memory. They dynamically generate the value of the element in the loop.
>>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: ... print(i) 0 1 4
This generator is almost the same as the list derivation. The only difference is that it uses parentheses () instead of brackets [] However, you can't use for i in mygenerator twice, because the generator can only be cycled once: they calculate 0x0 and return the result. They don't save it. The next time they call it, they calculate 1x1, and so on.
Yield
Fields is a keyword, which can be understood as the same as return. The difference is that it returns a generator
>>> def createGenerator(): ... mylist = range(3) ... for i in mylist: ... yield i*i ... >>> mygenerator = createGenerator() # create a generator >>> print(mygenerator) # mygenerator is an object! <generator object createGenerator at 0xb7555c34> >>> for i in mygenerator: ... print(i) 0 1 4
In the above example, the range is created first, which has occupied memory, but the square number does not. This example is not very good. This is given by the original author. There should be a better example in my video.
First of all, because of the existence of yield, when you call the above function, the code in it does not execute, instead of returning a Generator.
Then there are the key points:
- When the for loop calls the generator for the first time, it will execute from scratch until the yield keyword returns the first value, that is, 0.
- Then remember which line of code to execute, that is, the position of yield.
- The next time the for loop calls it again, it continues to execute from the next line of yield until it meets yield again and returns the next value, that is, 1
- This process is repeated until there is no content in the generator. In the example, the number in range is used up.
Now let's look at the first question:
This is a tree traversal algorithm to find qualified nodes on the tree. Detailed Chinese comments are added to the code.
Generator:
# This function returns a generator, which is a method in the node object of a binary tree def _get_child_candidates(self, distance, min_dist, max_dist): # If there is a left child and the distance meets the conditions, return to the left child and pause here if self._leftchild and distance - max_dist < self._median: yield self._leftchild # If there is a right child and the distance meets the conditions, return to the right child and pause here if self._rightchild and distance + max_dist >= self._median: yield self._rightchild # If the execution reaches this point, it means that there are no qualified left and right children, the generator is empty, and the iteration is over.
Caller:
# Create an empty list with the current object node result, candidates = list(), [self] # Cycle, there is only yourself in the beginning while candidates: # Pop up the last node node = candidates.pop() # Get the distance between obj object and target node distance = node._get_dist(obj) # If the distance is ok, write it to the result list if distance <= max_dist and distance >= min_dist: result.extend(node._values) # Add your child nodes to candidates, and the loop will continue until all nodes in the tree are traversed candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result
About Python technology reserve
It's good to learn Python well, whether in employment or sideline, but to learn python, you still need to have a learning plan. Finally, let's share a full set of Python learning materials to help those who want to learn Python!
1, Python learning routes in all directions
All directions of Python is to sort out the commonly used technical points of Python and form a summary of knowledge points in various fields. Its purpose is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.
2, Learning software
If a worker wants to do well, he must sharpen his tools first. The commonly used development software for learning Python is here, which saves you a lot of time.
3, Getting started video
When we watch videos, we can't just move our eyes and brain without hands. The more scientific learning method is to use them after understanding. At this time, the hand training project is very suitable.
4, Actual combat cases
Optical theory is useless. We should learn to knock together and practice, so as to apply what we have learned to practice. At this time, we can make some practical cases to learn.
5, Interview materials
We must learn Python in order to find a high paying job. The following interview questions are the latest interview materials from front-line Internet manufacturers such as Alibaba, Tencent and byte, and Alibaba boss has given authoritative answers. After brushing this set of interview materials, I believe everyone can find a satisfactory job.