Introduction
Looking for a python development job? Then you'll probably have to prove that you know how to use Python. The following questions relate to many of the skills associated with Python, and the focus is on the language itself, not on a particular package or module. Each problem can be expanded into a tutorial, if possible. Some issues may even involve multiple areas.
I haven't had any questions as difficult as these, and if you can answer them easily, get a job!
Question 1
What exactly is Python? You can compare it to other techniques in the answer (and encourage it).
Answer
Here are some key points:
- Python is an interpreted language. This means that unlike C and C's derived languages, Python code does not need to be compiled before it can run. Other explanatory languages include PHP and Ruby.
- Python is a dynamic type language, meaning that you do not need to describe the type of a variable when declaring it. You can write similar
x=111
and x="I‘m a string"
such code directly, the program will not error.
- Python is ideal for object-oriented programming (OOP) because it supports the definition of classes (class) by combining (composition) and Inheritance (inheritance). There is no access specifier in Python (access specifier, like in C + +
public
private
), so the design is based on "everyone is an adult."
- In the Python language, a function is the first class of objects (first-class objects). This means that they can be assigned to a variable, and the function can either return the function type or accept the function as input. Class is also the first class of objects.
- Python code is written fast, but runs slower than the compiled language. Fortunately, Python allows for the inclusion of extensions written in C language, so we can optimize the code to eliminate bottlenecks, which is usually achievable.
numpy
is a good example of how fast it works, because many arithmetic operations are not actually implemented by Python.
- Python is very versatile-Web applications, automation, scientific modeling, big data applications, and more. It is also often used as a "glue language" to help other languages and components improve health.
- Python makes difficult things easier, so programmers can focus on the design of algorithms and data structures without having to deal with the underlying details.
Why ask this question :
If you are applying for a Python development post, you should know what language it is and why it is so cool. And where it's not good.
Question 2
Add missing code
def print_directory_contents (spath): "" " this function takes the name of the folder as an input parameter, returns the path to the file in that folder, and the path to the file in the folder that contains it. "" " # Supplemental Code
Answer
def print_directory_contents (spath): import os for Schild in Os.listdir (spath): Schildpath = Os.path.join (Spath,schild) If Os.path.isdir (schildpath): print_directory_contents (Schildpath) else: print Schildpath
Special attention should be paid to the following points:
- The naming convention should be unified. If you can see the naming convention in the sample code, follow its existing specifications.
- Recursive functions require recursion to terminate. Make sure you understand the principle, or you will face the endless call stack (callstack).
- We use
os
modules to interact with the operating system while interacting in a way that can be cross-platform. You can write the code sChildPath = sPath + ‘/‘ + sChild
, but this will make an error on the Windows system.
- It is very valuable to be familiar with the basic module, but don't try to memorize it, remember that Google is your mentor at work.
- If you don't understand the expected functionality of the code, ask it boldly.
- Stick to the KISS principle! Keep it simple, but your mind will understand!
Why ask this question :
- Explain the interviewer's basic knowledge of interacting with the operating system
- Recursion is so good.
Question 3
Read the code below to write the final value of A0,A1 to an.
A0 = dict (Zip (' A ', ' B ', ' C ', ' d ', ' E '), (1,2,3,4,5))) A1 = Range (Ten) A2 = [i-I in A1 if i in a0]a3 = [A0[s] for s in a0]a4 = [I for I in A1 if I in A3] A5 = {I:i*i for i in a1}a6 = [[I,i*i] for i in A1]
Answer
A0 = {' A ': 1, ' C ': 3, ' B ': 2, ' E ': 5, ' d ': 4}a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]a2 = []A3 = [1, 3, 2, 5, 4]a4 = [1, 2, 3, 4, 5]a5 = {0:0, 1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81}a6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Why ask this question :
- List comprehension is a great time saver and a big learning hurdle for many people.
- If you read the code, it is possible to write down the correct values.
- Some of the code was deliberately written strangely. Because the people you work with are also weird.
Question 4
Python and Multithreading (multi-threading). Is this a good idea? List some of the ways that Python code runs in parallel.
Answer
Python does not support real-world multithreading. Multithreaded packages are available in Python, but it is not a good idea to use multithreaded packages if you want to increase the speed of your code through multithreading. Python has a thing called Global Interpreter Lock (GIL) that will make sure that only one of your multiple threads is executed at any time. Threads execute so quickly that you mistakenly assume that threads are executed in parallel, but in fact they are performed in turn. The cost of execution is increased by this level of Gil processing. This means that if you want to improve the speed of your code, it's threading
not a good way to use a package.
But there are a lot of reasons why we use threading
packages. If you want to perform some tasks at the same time and do not consider efficiency issues, then using this package is perfectly fine and convenient. But most of the time, that's not the case, you'll want to outsource the multithreaded parts to the operating system (by opening multiple processes), or some external program that calls your Python code (for example, Spark or Hadoop). or other code called by your Python code (for example, you can call C functions in Python to handle expensive multithreaded work).
Why do you ask this question?
Because Gil is a darn Thing (a-hole). Many people spend a lot of time trying to find bottlenecks in their multithreaded code until they understand the existence of the Gil.
Question 5
How do you manage different versions of code?
Answer :
Version Management! When asked this question, you should be very excited and even tell them how you use Git (or other favorite tools) to track your correspondence with your grandmother. I prefer to use Git as a version control system (VCS), but there are other options, such as Subversion (SVN).
Why ask this question :
Because there is no version-controlled code, it's like coffee without a cup. Sometimes we need to write a one-time script that you can throw away, which doesn't matter if you're not versioning. But if you're dealing with a lot of code, it's advantageous to use a version control system. Versioning can help you track who did what to the code base, discover what bugs were introduced, manage different versions and distributions of your software, share source code with team members, deploy, and other automated processes. It gives you the ability to roll back to the previous version of the problem, which is especially good. There are other good features as well. What a good word!
Question 6
What the following code will output:
def f (x,l=[]): For I in range (x): l.append (i*i) print LF (2) f (3,[3,2,1]) F (3)
Answer :
[0, 1] [3, 2, 1, 0, 1, 4] [0, 1, 0, 1, 4]
Uh?
The first function call is obvious, with the for loop adding 0 and 1 to the empty list l
. l
is the name of the variable, pointing to a list stored in memory. The second function call creates a new list in a new piece of memory. l
this points to the newly generated list. Then add 0, 1, 2, and 4 to the new list. It's great. The result of the third function call is a bit strange. It uses the old list stored in the previous memory address. That's why its first two elements are 0 and 1.
If you don't understand, try running the following code:
L_mem = []l = L_mem # The first callfor I in range (2): l.append (i*i) print L # [0, 1]l = [3,2,1] # the SEC Ond callfor i in range (3): l.append (i*i) print L # [3, 2, 1, 0, 1, 4]l = L_mem # The third callfor I in rang E (3): l.append (i*i) print L # [0, 1, 0, 1, 4]
Question 7
What does "Monkey Patch" (monkey patching) mean? Is this a good practice?
Answer :
"Monkey Patch" means to change the behavior of a function or object after it has been defined.
As an example:
Import Datetimedatetime.datetime.now = Lambda:datetime.datetime (2012, 12, 12)
In most cases, this is a very bad practice-because the function in the code base is best behaved consistently. The reason for playing "monkey Patch" may be to test. The mock
package is very helpful for this purpose.
Why do you ask this question ?
The answer to this question indicates that you have some knowledge of the method of unit testing. If you mention that you want to avoid "monkey patches," you can say that you're not the kind of programmer who likes fancy code (people in the company, it sucks to work with them), but more on maintainability. Remember the KISS principle code? The answer to this question also means that you understand some of the ways that Python works at the bottom, how the function is actually stored, called, and so on.
Plus: If you haven't read the mock
modules, it's really worth the time to read them. This module is very useful.
Question 8
What do these two parameters mean: *args
, **kwargs
? Why should we use them?
Answer
If we are not sure how many arguments we want to pass into the function, or if we want to pass the arguments as lists and tuples in the function, then it will be used *args
if we do not know how many keyword parameters to pass into the function, or if we want to pass in the dictionary value as a keyword parameter **kwargs
. args
and kwargs
These two identifiers are used in a conventional way, of course you can use *bob
and **billy
, but this is not very good.
Here's a concrete example:
def f (*args,**kwargs): print args, Kwargsl = [1,2,3]t = (4,5,6) d = {' A ': 7, ' B ': 8, ' C ': 9}f () f (All-in-All) # (1, 2, 3) {}f ("Groovy") # (1, 2, 3, ' groovy ') {}f (a=1,b=2,c=3) # () {' A ': 1, ' C ': 3, ' B ': 2}f (a= 1,b=2,c=3,zzz= "HI") # () {' A ': 1, ' C ': 3, ' B ': 2, ' zzz ': ' Hi '}f (1,2,3,a=1,b=2,c=3) # (1, 2, 3) {' A ': 1, ' C ': 3, ' B ': 2}f (*l,**d) # (1, 2, 3) {' A ': 7, ' C ': 9, ' B ': 8}f (*t,**d) # (4, 5, 6) {' A ': 7, ' C ': 9, ' B ': 8}f (1,2,*t) # (1, 2, 4, 5, 6) {}f (q= "winning", **d) # () {' A ': 7, ' Q ': ' Winning ', ' C ': 9, ' B ': 8}f (1,2,*t,q= "winning", **d) # (1, 2, 4, 5, 6) {' A ': 7, ' Q ': ' Winning ', ' C ': 9, ' B ': 8}def F2 (Arg1,arg2,*args, **kwargs): Print arg1,arg2, args, kwargsf2 (all in a) # 1 2 (3,) {}f2 ("Groovy") # 1 2 (3, ' Groovy ') {}f2 (arg1=1,arg2=2,c=3) # 1 2 () {' C ': 3}f2 (arg1=1,arg2=2,c=3,zzz= "HI") # 1 2 () {' C ': 3, ' zzz ': ' Hi '}f2 A=1,b=2,c=3) # 1 2 (3,) {' A ': 1, ' C ': 3, ' B ': 2}f2 (*l,**d) # 1 2 (3,) {' A ': 7, ' C ': 9, ' B ': 8}f2 (*t,**d # 4 5 (6,) {' A ': 7, ' C ': 9, ' B ': 8}f2 (1,2,*t) # 1 2 (4, 5, 6) {}f2 (1,1,q= "Winning", * *D) # 1 1 () {' A ': 7, ' Q ': ' Winning ', ' C ': 9, ' B ': 8}f2 (1,2,*t,q= "winning", **d) # 1 2 (4, 5, 6) {' A ': 7, ' Q ': ' Winn ing ', ' C ': 9, ' B ': 8}
Why do you ask this question ?
Sometimes we need to pass an unknown number of arguments or keyword parameters to the function. Sometimes we also want to store parameters or keyword parameters for later use. Sometimes, it's just to save time.
Question 9
What does the following mean: @classmethod
, @staticmethod
, @property
?
Answer background knowledge
These are adorners (decorator). An adorner is a special function that either accepts a function as an input parameter and returns a function that accepts a class as an input parameter and returns a class. The @ tag is a syntactic sugar (syntactic sugar) that allows you to decorate a target object in a simple, easy-to-read manner.
@my_decoratordef My_func (stuff): do_thingsis equivalent todef my_func (stuff): Do_thingsmy_func = My_ Decorator (My_func)
You can find a textbook that describes how the decorator works on this website.
The real answer
@classmethod
, @staticmethod
and @property
the objects used for these three adorners are functions defined in the class. The following examples illustrate their usage and behavior:
Class MyClass (object): Def __init__ (self): Self._some_property = "Properties is nice" self._some_other_p Roperty = "VERY Nice" def Normal_method (*args,**kwargs): print "calling Normal_method ({0},{1})". Format (Args,kwar GS) @classmethod def class_method (*args,**kwargs): print "calling Class_method ({0},{1})". Format (Args,kwargs) @staticmethod def static_method (*args,**kwargs): print "calling Static_method ({0},{1})". Format (Args,kwargs) @property def some_property (Self,*args,**kwargs): print "calling Some_property getter ({0},{1},{2})". Format (SEL F,args,kwargs) return Self._some_property @some_property. Setter def some_property (Self,*args,**kwargs): Print "Calling Some_property Setter ({0},{1},{2})". Format (Self,args,kwargs) Self._some_property = args[0] @prop Erty def some_other_property (Self,*args,**kwargs): print "calling Some_other_property getter ({0},{1},{2})". Forma T (Self,args,kwargs) return Self._some_other_propertyo = MyClass () # The method that is not decorated is still the normal way of behaving, requiring the current class instance (self) as the first argument. O.normal_method # <bound Method Myclass.normal_method of <__main__. MyClass instance at 0x7fdd2537ea28>>o.normal_method () # Normal_method ((<__main__. MyClass instance at 0x7fdd2537ea28>,), {}) O.normal_method (1,2,x=3,y=4) # Normal_method ((<__main__. MyClass instance at 0x7fdd2537ea28>, 1, 2), {' Y ': 4, ' X ': 3} ' # The first parameter of a class method is always the class o.class_method# <bound method classobj.c Lass_method of <class __main__. MyClass at 0x7fdd2536a390>>o.class_method () # Class_method ((<class __main__. MyClass at 0x7fdd2536a390>,), {}) O.class_method (1,2,x=3,y=4) # Class_method ((<class __main__. MyClass at 0x7fdd2536a390>, 1, 2), {' Y ': 4, ' X ': 3}] # There are no other parameters in the static method except for the arguments passed in when you call. o.static_method# <function Static_method at 0x7fdd25375848>o.static_method () # Static_method ((), {}) O.static_ Method (1,2,x=3,y=4) # Static_method ((1, 2), {' Y ': 4, ' X ': 3}) # @property is a way to implement getter and setter methods. Call directlyThey are wrong. # The Read-only property can be implemented by defining only the Getter method and not the setter method. o.some_property# calls Some_property's getter (<__main__. MyClass instance at 0x7fb2b70877e8>, (), {}) # ' Properties is nice ' # "attribute" is a good feature o.some_property () # Calling Some_ Property Getter (<__main__. MyClass instance at 0x7fb2b70877e8>, (), {}) # Traceback (most recent call last): # File ' <stdin> ', line 1, in < module># TypeError: ' str ' object is not callableo.some_other_property# calling Some_other_property getter (<__main __. MyClass instance at 0x7fb2b70877e8>, (), {}) # ' VERY Nice ' # o.some_other_property () # Calling Some_other_property Getter (<__main__. MyClass instance at 0x7fb2b70877e8>, (), {}) # Traceback (most recent call last): # File ' <stdin> ', line 1, in < module># TypeError: ' str ' object is not Callableo.some_property = "Groovy" # Calling Some_property Setter (<__main__. MyClass object at 0x7fb2b7077890>, (' Groovy ',), {}) o.some_property# calling Some_property getter (<__main__. MyClass Object at 0x7fb2b7077890>, (), {}) # ' groovy ' O.some_other_property = ' very Groovy ' # Traceback (most recent call last): # File "<stdin>", Line 1, in <module># attributeerror:can ' t set attributeo.some_other_property# calling Some_other_property getter ( <__main__. MyClass object at 0x7fb2b7077890>, (), {})
Question 10
Read the following code, what is the output of it?
Class A (object): def Go (self): print "Go A go!" def stop (self): print "Stop A stop!" def pause (self): raise Exception (' not implemented ') class B (A): def go: super (B, self). Go () Print "Go B go!" Class C (A): def go: super (C, self). Go () print "Go C go!" def stop (self): super (C, self). Stop () print "Stop C stop!" Class D (B,c): def go: super (d, self). Go () print "Go D go!" def stop (self): super (D, self). Stop () print "Stop D stop!" def pause (self): print "Wait D wait!" Class E (b,c): Passa = A () b = b () c = C () d = d () e = e () # Describes the output of the following code A.go () B.go () C.go () D.go () E.go () A.stop () B.stop () C.stop () d. Stop () e.stop () A.pause () B.pause () C.pause () D.pause () E.pause ()
Answer
The output is expressed as a note:
A.go () # Go a go!b.go () # go a go!# Go B go!c.go () # Go a go!# go C go!d.go () # Go a go!# go C go!# go b go!# go D go!e.go () # Go a go!# go C go!# go B go!a.stop () # Stop A stop!b.stop () # Stop A stop!c.stop () # Stop a stop!# stop C stop!d.stop () # Stop A stop!# stop C stop!# stop D stop!e.stop () # Stop A stop!a.pause () # ... Exception:not implementedb.pause () # ... Exception:not implementedc.pause () # ... Exception:not Implementedd.pause () # wait D wait!e.pause () # ... Exception:not implemented
Why do you ask this question ?
Because object-oriented programming is really really important. Don't lie to you. The answer to this question shows that you understand the use of functions in inheritance and Python super
.
Question 11
Read the following code, what is the output of it?
Class Node (object): Def __init__ (self,sname): Self._lchildren = [] Self.sname = SName def __repr__ (sel f): Return "<node ' {} ' >". Format (Self.sname) def append (Self,*args,**kwargs): Self._lchildren.append (*args,**kwargs) def print_all_1 (self): print self for ochild in Self._lchildren:ochild.print _all_1 () def print_all_2 (self): def gen. (o): LAll = [O,] while lall:onext = Lall.pop (0) lall.extend (onext._lchildren) yield onext for Onode in Gen (self): Print Onodeoroot = node ("root") OChild1 = node ("child1") OChild2 = node ("child2") oChild3 = node ("child3") OChild4 = node ("Child4") OChild5 = node ("child5") OChild6 = node ("Child6") OChild7 = node ("Child7") OChild8 = node ("Child8") OCHILD9 = node ("child9") OChild10 = Node ("Child10") oroot.append (oChild1) oroot.append (oChild2) oroot.append (OCHILD3) Ochild1.append (OCHILD4) ochild1.append (OCHILD5) oChIld2.append (OCHILD6) ochild4.append (OCHILD7) ochild3.append (OCHILD8) ochild3.append (OCHILD9) ochild6.append ( OCHILD10) # Describes the output of the following code Oroot.print_all_1 () oroot.print_all_2 ()
Answer
oRoot.print_all_1()
The following results are printed:
<node ' root ' ><node ' child1 ' ><node ' child4 ' ><node "Child7 ' ><node ' child5 ' ><node ' Child2 ' ><node ' child6 ' ><node ' child10 ' ><node "child3 ' ><node ' child8 ' ><node ' child9 ' >
oRoot.print_all_1()
The following results are printed:
<node ' root ' ><node ' child1 ' ><node ' child2 ' ><node "child3 ' ><node ' child4 ' ><node ' Child5 ' ><node ' child6 ' ><node ' Child8 ' ><node "child9 ' ><node ' child7 ' ><node ' child10 ' >
Why do you ask this question ?
Because the essence of an object is the combination (composition) and the object construction (object construction). Objects need to be composed of composition components and initialized in some way. This also involves the use of recursion and generators (generator).
The generator is a great data type. You can just construct a very long list and then print the contents of the list, and you can get print_all_2
similar functionality. The generator also has the benefit of not having to occupy a lot of memory.
It is also worth pointing out that the print_all_1
tree is traversed in a depth-first (depth-first) manner, while the print_all_2
width first (width-first). Sometimes one way of traversing is more appropriate than the other. But it depends on the specifics of your application.
Question 12
A brief description of the Python garbage collection mechanism (garbage collection).
Answer
There's a lot to say here. You should mention the following key points:
- Python stores a reference count (reference count) for each object in memory. If the count value becomes 0, the corresponding object will be in the hour and the memory allocated to the object will be freed for use.
- Occasionally it will appear
引用循环
(reference cycle). The garbage collector periodically looks for the loop and recycles it. For example, suppose there are two objects o1
and o2
that are consistent with o1.x == o2
and both o2.x == o1
conditions. If o1
and o2
no other code references, then they should not continue to exist. But they have a reference count of 1.
- Some heuristic algorithms (heuristics) are used in Python to speed up garbage collection. For example, the later created objects are more likely to be recycled. After the objects are created, the garbage collector assigns the generation (generation) to which they belong. Each object is assigned a generation, and the objects that are assigned to the younger generation are processed preferentially.
Question 13
The following functions are sorted by execution efficiency. They all accept a list of numbers from 0 to 1 as input. This list can be very long. An example of an input list is as follows: [random.random() for i in range(100000)]
. How do you prove that your answer is correct?
Def F1 (Lin): L1 = sorted (lin) L2 = [I for I in L1 if i<0.5] return [i*i-I in L2]def F2 (Lin): l1 = [ I for I in Lin if i<0.5] L2 = sorted (L1) return [i*i for I in L2]def F3 (Lin): l1 = [I*i for i in Lin] l 2 = sorted (L1) return [i-I in L1 if i< (0.5*0.5)]
Answer
Ranked by execution efficiency from high to Low: F2, F1 and F3. To prove that the answer is correct, you should know how to analyze the performance of your code. Python has a good program analysis package to meet this requirement.
Import Cprofilelin = [Random.random () for I in range (100000)]cprofile.run (' F1 (Lin) ') Cprofile.run (' F2 (Lin) ') Cprofile.run (' F3 (LIn) ')
To give you a complete explanation, the output of the above analysis code is given below:
>>> Cprofile.run (' F1 (lIn) ') 4 function calls in 0.045 seconds Ordered by:standard name Ncalls Totti Me percall cumtime percall filename:lineno (function) 1 0.009 0.009 0.044 0.044 <stdin>:1 (F1) 1 0.001 0.001 0.045 0.045 <string>:1 (<module>) 1 0.000 0.000 0.000 0.000 {method ' disable ' of ' _lsprof. Profiler ' objects} 1 0.035 0.035 0.035 0.035 {sorted}>>> cprofile.run (' F2 (lIn) ') 4 Fun Ction calls in 0.024 seconds Ordered by:standard name ncalls tottime percall cumtime percall Filename:lineno (func tion) 1 0.008 0.008 0.023 0.023 <stdin>:1 (F2) 1 0.001 0.001 0.024 0.024 <st Ring>:1 (<module>) 1 0.000 0.000 0.000 0.000 {method ' disable ' of ' _lsprof. Profiler ' objects} 1 0.016 0.016 0.016 0.016 {sorted}>>> cprofile.run (' F3 (LIn) ') 4 Fun Ction calls in 0.055 seconds Ordered by:standard name ncalls tottime percall cumtime percall Filename:lineno (function) 1 0.016 0.016 0.054 0.054 <stdin>:1 (F3) 1 0.001 0.001 0.055 0.055 <string>:1 (< ;module>) 1 0.000 0.000 0.000 0.000 {method ' disable ' of ' _lsprof. Profiler ' objects} 1 0.038 0.038 0.038 0.038 {sorted}
Why do you ask this question ?
Locating and avoiding code bottlenecks is an invaluable skill. To write a lot of efficient code and ultimately to answer common sense-in the example above, if the list is smaller, it is obvious that sorting is quicker first, so it's usually better if you can filter before sorting. Other non-obvious problems can still be located through the right tools. So it's good to know about these tools.
Question 14
Have you ever had any experience of failure?
The wrong answer
I have never failed!
Why do you ask this question ?
A proper answer to this question means that you are used to acknowledge errors, take responsibility for your own mistakes, and be able to learn from your mistakes. All of this is especially important if you want to become helpful to others. If you are really perfect, that's too bad, you may be a little creative when you answer this question.
Question 15
Have you ever implemented a personal project?
It's true?
If you have done a personal project, it means that you are willing to do more than the minimum required to update your skill level. If you have a personal project that you maintain, and you stick to coding outside of your job, your employer is more likely to see you as an asset that will add value. Even if they don't ask this question, I think it would be helpful to talk about this topic.
Conclusion
When I give these questions, I intentionally involve a number of areas. And the answer is deliberately written more verbose. In a programming interview, you need to show your understanding of the language, and if you can explain it briefly, be sure to do that. I try to provide enough information in the answer, even if you have never known these areas before, you can learn something from the answer. I hope this article will help you find a satisfactory job.
Come on!
SOURCE Link: http://codingpy.com/article/essential-python-interview-questions/
15 questions to see in Python interview