Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions for the Python Program?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the interview questions for Python collaboration". In the daily operation, I believe that many people have doubts about the interview questions of Python collaboration. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the questions of "what are the interview questions of Python collaboration?" Next, please follow the editor to study!

I. what is a cooperative process?

Collaborative process: to achieve collaborative multitasking, you can interrupt within the execution of the program and switch to other cooperative programs.

For example, when we write subroutines (or functions), we usually use "calls" to jump from A to B, B to C. if we want to come back to the caller, we must wait for the callee to finish executing. The whole calling process is realized through the stack. On the other hand, the co-program "interrupts" in the process of running the subroutine, turns to execute other subroutines, and then comes back to run at the appropriate time.

Second, the difference between co-program and thread

The advantages of co-programming over threads:

1. The efficiency of cooperative process is higher than that of thread. Switching between threads requires overhead, while inter-program switching is controlled by the program itself and does not require overhead.

2. The cooperative program does not need the locking mechanism of multi-thread. The co-program is switched in a thread, so there is no conflict between writing variables at the same time, and there is no need to lock the shared resource, only to judge the state.

PS: if you want to use multiple CPU, you can use process + co-program.

Third, the realization of the cooperative process

The co-program is implemented through yield, so the co-program is the generator and can be called through next.

Def simple (a): print ("- start----") r = yield a print ('- start----'+ str (r)) > my_simple = simple (5) > > my_simple > next (my_simple)-start----5 > my_simple.send (8)-r-8Traceback (most recent call last): File ", line 1, in StopIteration

As you can see, my_simple is a generator instance, which needs to use the next () method or send (None) to preactivate the co-program, which stops when the co-program runs to yield. When the send () method is used to assign a value to yield, the program continues to run down and throws a StopIteration exception.

Fourth, the return value of the cooperative journey

After the python3.3 version, the co-program can have a return value.

Def simple (a): print ("- start----") r = yield a print ('- start----'+ str (r)) return r > my_simple = simple (5) > next (my_simple)-start----5 > my_simple.send (8)-r-8Traceback (most recent call last): File ", line 1, in StopIteration: 8

You can see that after the program is run, the value property of the exception object StopIteration holds the returned value.

5. Use yield from to get the return value of the cooperative program.

For yield from, the interpreter not only catches StopIteration exceptions, but also takes the value of the value attribute as the value of the yield from expression.

The main function of yield from is to open a two-way channel and connect the outermost caller to the innermost child generator.

# Sub-generator def total_num (): total = 0 while True: num = yield if num = = None: break total + = num return total# delegated generator def send_num (result, key): while True: result [key] = yield from total_num () # caller def main (data): result = {} for key, nums in data.items (): group = send_num (result Key) next (group) for num in nums: group.send (num) group.send (None) print (result) data = {'nums1': [12, 34, 23, 4, 35, 34, 34, 55],' nums2': [22, 44, 33, 24, 33, 33, 24, 4, 15], 'nums3': [32, 54, 43, 41, 31, 44, 24, 25],' nums4': [42, 64, 53, 43, 37, 74, 74, 35] 'nums5': [52, 74, 63, 46, 39, 84, 44, 45]} if _ _ name__ = "_ _ main__": main (data)

The output is as follows:

{'nums1': 231,' nums2': 199, 'nums3': 294,' nums4': 422, 'nums5': 447}

The delegate generator connects the caller and the sub-generator as a two-way pipeline. When the delegate generator pauses at the yield from expression, the caller passes the data to the sub-generator through the send () method, and the sub-generator sends the output value to the caller. When the sub-generator returns, it throws a StopIteration exception and adds the return value to the exception value attribute, and the exception generator will restore it. And get the value of the exception as the value of the yield from expression.

A delegate generator is equivalent to a pipe, so you can connect any delegate generator: the child generator to which the delegate generator connects is a delegate generator, and so on, until you encounter a generator that uses yield or an iterable object.

VI. Summary

1. The cooperative program is used to control program interrupts, which is different from function calls.

2. The cooperative program can handle multi-tasks in a single thread, which saves the overhead of thread switching compared with multi-thread.

3. The cooperative program is implemented through the yield keyword, which is also a generator.

4. The caller of the co-program can send the value to the callee through the send () method. The opening of the cooperative program requires preexcitation, and the preexcitation method is: send (None) or next ()

5. The cooperative program has a return value after python3.3, and the returned value will be placed in the value of the StopIteration exception.

6. The function of yield from is to call the sub-generator in the generator, which can optimize a complex code such as a nested for loop.

7. There are four states of a collaborative program: GEN_CREATED (waiting for execution to start), GEN_RUNNING (interpreter is executing), GEN_SUSPENDED (stopping at yield expression), and GEN_CLOSED (execution ending). Through inspect.getgeneratorstate (...) Function can be obtained

8. There are two ways to end the collaborative process: generator.throw or generator.close

7. Relevant interview questions

The concept of Python learning process is introduced above, and several interview questions about it are provided here.

Combining theory with "interview"

1. What are processes, threads, and collaborators?

Main points of the answer:

A, the process is a resource allocation, each process has an independent resource space, because the process does not share resources, so it involves the way of inter-process communication, common ways are: message queue, pipeline, semaphore, socket socket and so on. (here are several interview questions: what are the ways of communication between processes? -> which message queues have been used? )

B. Thread (English: thread) is the smallest unit that the operating system can schedule operations. It is included in the process and is the actual operating unit of the process. Threads are under a process, so multiple threads under the same process can share resources. The resources that threads can share are heaps, global variables, file descriptors and signal processing, etc., and unshared resources: stacks, registers, etc. (here will lead to the interview question: how to achieve multithreading? -> Multithreading concurrency problem-> which resources are shared by multithreading)

C. The cooperative program implements multitasking under a single thread, which is realized by the yield keyword, which can effectively reduce the overhead of switching between multithreads. It is a more lightweight presence than threads. Just as a process can have multiple threads, a thread can have multiple collaborators.

2. What are the advantages and disadvantages of the cooperative process?

Main points of the answer

A, the cooperative program is not managed by the operating system kernel, but is completely controlled by the program (that is, executed in the user mode), the performance has been greatly improved, and will not consume resources like thread switching.

B, disadvantages: asynchronous code, which may not be easy to understand and schedule

3. What is the output of the following code?

Def test (): print ("1" * 30) yield "A" print ("A" * 30) yield "B" print ("B" * 30) t = test () # 1print (next (t)) # 2print (next (t)) # 3print (next (t)) # 4

Main points of the answer:

This is actually a topic belonging to the generator, and the output is as follows:

1: there is no output, it does not execute print ("1" * 30), it only returns a generator

2: output "111... 111" (30) and print the return value "A"

3: output "111... 111" (30) and print the return value "B"

4: exception, StopIteration

4. Please write a simple example of collaboration or use it to implement a producer-consumer model.

In fact, the interview is generally less said to ask the interviewer to write a collaborative code by hand, but there has been a handwritten one that uses the collaborative process to implement the producer-consumer model before.

Import timedef consumer (): r =''while True: n = yield r if not n: return print (' [CONSUMER] Consuming% s.n) time.sleep (1) r = '200 OK'def produce (c): c.next () n = 0 while n < 5: n = n + 1 print (' [PRODUCER] Producing% s.'% n) r = c.send (n) print ('[PRODUCER] Consumer return:% s'r) # Termination method: generator.throw or generator.close c.close () if _ _ name__=='__main__': c = consumer () produce (c) so far The study on "what are the interview questions for Python Cooperation Program" is over. I hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report