程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interview questions

編輯:Python

1、 python Multithreading has a global interpreter lock (global interpreter lock), This lock means that only one thread can use the interpreter at any time , documentary cpu Running multiple programs means , Everyone is in turn , This is called “ Concurrent ”, No “ parallel ”.
Sharing data among multiple processes , have access to multiprocessing.Value and multiprocessing.Array. 2、 What is? lambda function ? What's the advantage of it ?
2、 lambda Function is a function that can take any number of parameters ( Including optional parameters ) A function that returns the value of a single expression .lambda Functions cannot contain commands , They cannot contain more than one expression . Don't try to talk to lambda Too many things in the function ; If you need something more complicated , You should define a normal function , And make it as long as you want .
3、Python How to do type conversion ? ① Function description
② int(x [,base ]) take x Convert to an integer ③long(x [,base ]) take x Convert to a long integer ④float(x ) take x Converts to a floating point number ⑤complex(real [,imag ]) Create a complex number ⑥str(x ) Put the object x Convert to string ⑦repr(x ) Put the object x Converts to an expression string
⑧eval(str ) Used to calculate the validity in a string Python expression , And returns an object ⑨tuple(s ) The sequence of s Converts to a tuple ⑩list(s ) The sequence of s Convert to a list ⑪chr(x ) Converts an integer to a character ⑫unichr(x ) Convert an integer to Unicode character ⑬ord(x ) Converts a character to its integer value ⑭hex(x ) Convert an integer to a hexadecimal string ⑮oct(x ) Converts an integer to an octal string 4、python The difference between multithreading and multiprocessing

                stay UNIX On the platform , When a process ends , This process needs to be called by its parent process wait, Otherwise the process becomes a zombie process (Zombie). therefore , It is necessary for each Process Object call join() Method ( Is actually equivalent to wait)

            . For multithreading , Because there is only one process , So there is no need . 
                Multiple processes should avoid sharing resources . In multithreading , We can share resources more easily , Such as using global variables or passing parameters . In a multi process situation , Because each process has its own independent memory space , The above method is not suitable . At this point we can share memory and Manager To share resources .
            But doing so increases the complexity of the program , And because of the need for synchronization and reduce the efficiency of the program . 5、Python
            How do I copy an object inside ? 
In the standard library copy The module provides two methods to realize copying . One way is copy, It returns the same object as the parameter contains . Use deepcopy Method , The properties in the object are also copied .            
1
2
3
4
5
6
7
6、 Introduce to you except Usage and function of ?
Python Of except Used to catch all exceptions , because Python Every error in it will throw an exception , So every program error is treated as a runtime error .
7 、Python in pass What is the function of the sentence ?
pass The statement does nothing , Generally as placeholders or create placeholders ,pass Statement does nothing .
8、Python Types and features of interpreter ?
Python It's an interpreter language , The code wants to run , Must be executed through interpreter ,Python There are many kinds of interpreters , Developed in different languages , Each interpreter has different characteristics , But they all work Python Code , Here are five commonly used Python Interpreter :
CPython: When from Python Download and install the official website Python2.7 after , You get an official version of the interpreter :Cpython, This interpreter uses C Language development , So called CPython, Run... Under the named line python, That is to start. CPython Interpreter ,CPython Is the most widely used Python Interpreter . IPython:IPython Is based on CPython An interactive interpreter on top , in other words ,IPython It's just a little bit more interactive , But to perform Python Code functions and CPython It's exactly the same , For example, many domestic browsers have different appearance , But the kernel is actually calling IE.
PyPy:PyPy Is another Python Interpreter , Its goal is speed of execution ,PyPy use JIT technology , Yes Python Dynamic compilation on behalf of , So it can be significantly improved Python Code execution speed .
Jython:Jython Is running on the Java On the platform Python Interpreter , You can directly Python Code compiled into Java Bytecode execution .
IronPython:IronPython and Jython similar , It's just IronPython It's running at Microsoft .Net On the platform Python Interpreter , You can directly Python Code compiled into .Net Bytecode .
stay Python In the interpreter of , Widely used is CPython, about Python Compilation of , In addition to picking

            Compile with the above interpreter , Highly skilled developers can also write their own Python The interpreter executes
      
            Python Code , Very convenient ! 9、 List Boolean values as
        False Common values for ?       
             0, [] , () , {} , '' , False , None 10、 character string 、 list 、 Tuples 、 Every commonly used Dictionary            
            5 A way ?                     
            character string :repleace,strip,split,reverse,upper,lower,join.....     
          list :append,pop,,remove,sort,count,index.....                 
            Tuples :index,count,__len__(),__dir__() 
            Dictionaries :get,keys,values,pop,popitems,clear,,items..... 11、lambda Expression format and application scenarios ? 
                Expression format :lambda Followed by one or more parameters , Follow a colon , And then there's an expression . The colon is preceded by a parameter , The colon is followed by the return value . for example :lambda x : 2x 

            Application scenarios : the
            Often with some built-in functions
            In combination with ,
            for instance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
map(),filter(),sorted(),reduce() etc.
12、pass The role of ?
① Empty statement do nothing;
② Ensure that the format is complete ;
③ Ensure semantic integrity . 13、arg
and *kwarg effect ?
Universal parameters , It solves the problem that the function parameters are not fixed
*arg: It converts the position parameter to tuple
**kwarg: Will convert keyword parameters to dict

14、is and == The difference between ?

               is: Determine if memory addresses are equal ;     ==: Determine whether the values are equal . 
1
15、 sketch Python Deep and shallow copies of and application scenarios ?
copy(): shallow copy, Shallow copy refers to copying only the first layer data of the data set deepcopy(): deep copy, Deep copy refers to copying all layers of a data set

16、Python Garbage collection mechanism ?
python It mainly adopts the reference counting mechanism , Mark - Clearing and generational collection ( Next generation recycling 、 Generational recycling ) A strategy supplemented by two mechanisms Counting mechanism :
Python Of GC The module mainly uses reference counting to track and recycle garbage . On the basis of reference counting , You can also use “ Mark - eliminate ”
Solves the problem of circular references that container objects may generate . Through generational recycling, space is exchanged for time to further improve the efficiency of garbage collection . Mark - eliminate :
Mark - The appearance of cleanup breaks the circular reference , That is, it only focuses on objects that may generate circular references .
shortcoming : The extra operations brought by this mechanism are directly proportional to the memory blocks to be reclaimed . Next generation recycling :

principle : All memory blocks in the system are divided into different sets according to their lifetime , Each set becomes
        
            
        
            For one “ generation ”, 

        
            
        
            The frequency of garbage collection follows “ generation ” The survival time of . in other words , The longer you live , The less likely it is to be garbage , 
We should reduce the frequency of garbage collection . So how to measure this survival time : It's usually measured by several garbage collection actions , 
If an object passes through more garbage collection times , We can draw : The longer the object lives . 17、python Variable and immutable types ? 
Immutable type ( Numbers 、 character string 、 Tuples 、 Immutable set ); 
        
            
        
                Variable type ( list 、 Dictionaries 、 Variable set ). 
        
            
        
            18、Python Inside search() and match() The difference between ? 
match() Function only detects RE Is it in string The start of the match ,search() Will scan the whole
        
            
        
            string Find a match , in other words match()
        
            
        
            Only in 0 If the location match is successful, it will return , If it's not the start position matching that works ,
        
            
        
            match() Just go back to none 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
19、 use Python matching HTML tag When ,<.> and <.?> What's the difference? ?
The former is greedy matching , Will match from beginning to end xyz, The latter is a non greedy match , Only match to the first >.
20、Python How to generate random numbers in it ? import random;
random.random();

2021 New year Python Interview questions and answers
1、Python How do I copy an object inside ?( assignment , Shallow copy , Deep copy difference )
answer : assignment (=), Is to create a new reference to the object , Modifying any one of these variables will affect the other .
Shallow copy : Create a new object , But it contains references to the items contained in the original object ( If you modify one of the objects by reference , The other one will change ){1, Complete sectioning ;2, Factory function , Such as list();3,copy Modular copy() function }
Deep copy : Create a new object , And recursively copy the objects it contains ( Modify one of , The other one won't change ){copy Modular () function }
2、Python Inside match() and search() The difference between ?
answer :re Module match(pattern,string[,flags]), Check string Whether the beginning of is related to pattern matching .
re Module research(pattern,string[,flags]), stay string Search for pattern The first matching value of .

print(‘super’, ‘superstition’).span())
(0, 5)
print(‘super’, ‘insuperable’))
None
print(‘super’, ‘superstition’).span())
(0, 5)
print(‘super’, ‘insuperable’).span())
(2, 7)
3、 Is there a tool that can help you find python Of bug And static code analysis ?
answer :PyChecker It's a python Static analysis tools for code , It can help find python Code bug, Warnings about the complexity and format of the code
Pylint It's another tool that can do codingstandard Check
4、 A brief description Python Garbage collection mechanism (garbage collection).
answer
There's a lot to say here . You should mention the following main points :
Python The reference count of each object is stored in memory (reference count). If the count becomes 0, Then the corresponding object will be hours , The memory allocated to the object is released for other purposes .
Occasionally, reference loops occur (reference cycle). The garbage collector will periodically look for this loop , And recycle it . for instance , Suppose there are two objects o1 and o2, And it's in line with == o2 and == o1 These two conditions . If o1 and o2 No other code references , Then they should not continue to exist . But their reference counts are 1.
Python Some heuristic algorithms are used in (heuristics) To speed up garbage collection . for example , Objects created later are more likely to be recycled . After the object is created , The garbage collector will allocate the generation to which they belong (generation). Each object is assigned a generation , Objects assigned to younger generations are treated first .
5、 What is? lambda function ? What's the advantage of it ?
answer :lambda expression , Usually you need a function , But I don't want to bother to name a function , That is, anonymous functions
lambda function : The primary purpose is to point to short callback functions
lambda [arguments]:expression
a=lambdax,y:x+y
a(3,11)
6、 Please write a paragraph Python Code implementation delete a list The repeating elements in it
answer :
1, Use set function ,set(list)
2, Use dictionary functions ,
a=[1,2,4,2,4,5,6,5,7,8,9,0]
b={}
b=(a)
c=list())
c
7、 use Python matching HTML tag When ,<.> and <.?> What's the difference? ?
answer : The term is greedy matching ( <.> ) Match non greed (<.?> )
for example :
test
<.> :
test
<.?> :
8、 How to function Set a global variable in it ?
answer : The solution is in function At the beginning of, insert a global Statement :
def f()
global x
9、 For programming sort Sort , Then judge from the last element
a=[1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
()
last=a[-1]
for i inrange(len(a)-2,-1,-1):
if last==a[i]:
del a[i]
else:last=a[i]
print(a)
10、 The following code is in Python2 What is the output of ? Explain your answer
def div1(x,y):
print “%s/%s = %s” % (x, y, x/y)

def div2(x,y):
print "%s2)
div2(5,2)
div2(5.,2.)
in addition , stay Python3 How does the output of the above code differ ( Let's say... In the code print The sentences are transformed into Python3 The grammatical structure of )?
stay Python2 in , The output of the code is :
5/2 = 2
2 =
52 The result is
Note that you can go through the following import Statement to cover Python2 This behavior in
from future import division
Also pay attention to “ Double slash ”(//) The operator will always perform an integral Division , Ignore the type of operands . That's why / Even in Python2 It turns out to be
But in Python3 There was no such act . When both operands are integers , And it doesn't do integer operations . stay Python3 in , Output is as follows :
5/2 =
2 =
5//2 = 2
/ =


Python Basic knowledge written test
One 、 Single topic selection (2.5 branch *20 topic )

  Which of the following expressions is in Python It's illegal ? B
1
A. x = y = z = 1
B. x = (y = z + 1)
C. x, y = y, x
D. x += y
2. python my.py v1 v2 Command run script , adopt from sys import argv How to get v2 Parameter values for ? C
A. argv[0]
B. argv[1]
C. argv[2]
D. argv[3]
3. How to interpret the following execution results ? B
print 1.2 - 1.0 == 0.2
False
A. Python There is an error in the implementation of
B. Floating point numbers cannot accurately represent
C. Boolean operations cannot be used for floating point comparisons
D. Python Will not 0 The number is regarded as False
4. What is the result of the following code execution ? D
x = 1
def change(a):
x+= 1
print x
change(x)
A. 1
B. 2
C. 3
D. Report errors
5. Which of the following types is Python The mapping type of ? D
A. str
B. list
C. tuple
D. dict
6. The following string formatting syntax is correct ? D
A. ‘GNU’s Not %d %%’ % ‘UNIX’
B. ‘GNU’s Not %d %%’ % ‘UNIX’
C. ‘GNU’s Not %s %%’ % ‘UNIX’
D. ‘GNU’s Not %s %%’ % ‘UNIX’
7. stay Python 2.7 in , Which of the following is Unicode The way the code is written ?C
A. a = ‘ chinese ’
B. a = r‘ chinese ’
C. a = u’ chinese ’
D. a = b’ chinese ’
8. The result of the following code is ? D
print ‘a’ < ‘b’ < ‘c’
A. a
B. b
C. c
D. True
E. False
9. The following code runs and the result is ? C
a = ‘a’
print a > ‘b’ or ‘c’
A. a
B. b
C. c
D. True
E. False
10. Which of the following is not Python How tuples are defined ? A
A. (1)
B. (1, )
C. (1, 2)
D. (1, 2, (3, 4))
11. a And b The definition is as follows , Which of the following is true ? B
a = ‘123’
b = ‘123’
A. a != b
B. a is b
C. a == 123
D. a + b = 246
12. The following misunderstandings of the collaborative process are ? D
A. A thread can run multiple coprocedures
B. The scheduling of the collaborative process is controlled by the program itself
C. Linux The scheduling of threads in is controlled by the operating system
D. Linux The scheduling of the middle process is controlled by the operating system
13. Which of the following function parameter definitions is illegal ? C
A. def myfunc(*args):
B. def myfunc(arg1=1):
C. def myfunc(*args, a=1):
D. def myfunc(a=1, args):
14. The execution result of the following code is ? A
[ii for i in xrange(3)]
A. [1, 1, 4]
B. [0, 1, 4]
C. [1, 2, 3]
D. (1, 1, 4)
15. A piece of code is defined as follows , The correct result of the following call is ?A
def bar(multiple):
def foo(n):
return multiple ** n
return foo
A. bar(2)(3) == 8
B. bar(2)(3) == 6
C. bar(3)(2) == 8
D. bar(3)(2) == 6
16. The following code runs the result ? C
a = 1
try:
a += 1
except:
a += 1
else:
a += 1
finally:
a += 1
print a
A. 2
B. 3
C. 4
D. 5
17. After the following code runs ,a、b、c、d The values of four variables , The wrong description is ? D
import copy
a = [1, 2, 3, 4, [‘a’, ‘b’]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
a.append(5)
a[4].append(‘c’)
A. a == [1,2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
B. b == [1,2, 3, 4, [‘a’, ‘b’, ‘c’], 5]
C. c == [1,2, 3, 4, [‘a’, ‘b’, ‘c’]]
D. d == [1,2, 3, 4, [‘a’, ‘b’, ‘c’]]
18. There are the following function definitions , The correct result is ? A
def dec(f):
n = 3
def wrapper(*args,**kw):
return f(*args,**kw) * n
return wrapper

@dec
def foo(n):
return n * 2
A. foo(2) == 12
B. foo(3) == 12
C. foo(2) == 6
D. foo(3) == 6
19. There are the following class definitions , The following description is wrong ? D
class A(object):
pass

class B(A):
pass

b = B()
A. isinstance(b, A) == True
B. isinstance(b, object) == True
C. issubclass(B, A) == True
D. issubclass(b, B) == True
20. The following code runs and the result is ? C
a = map(lambda x: x**3, [1, 2, 3])
list(a)
A. [1, 6, 9]
B. [1, 12, 27]
C. [1, 8, 27]
D. (1, 6, 9)
Two 、 Multiple choice (5 branch 5 topic )
21. Python Middle function is an object , The right description is ? ABCD
A. Function can be assigned to a variable
B. Functions can be added to collection objects as elements
C. Functions can be passed as parameter values to other functions
D. A function can be used as the return value of a function
22. if a = range(100), Which of the following is legal ? ABCD
A. a[-3]
B. a[2:13]
C. a[::3]
D. a[2-3]
23. if a = (1, 2, 3), Which of the following is legal ? ABD
A. a[1:-1]
B. a3
C. a[2] = 4
D. list(a)
24. Python Middle single underline _foo And double underline __foo And __foo__ Members of , The following statement is correct ?ABC
A. _foo Can't be used directly for ’from module import ’
B. __foo The parser uses _classname__foo To replace the name , With the same name as other classes
C. __foo__ representative python A special way of marking
D. __foo Can be used directly ’from module import ’
25. __new__ and __init__ The difference between , It's true that ? ABCD
A. new__ It's a static method , and __init__ Is an example method
B. new__ Method returns a created instance , and __init__ Nothing back
C. Only in __new__ Return to one cls When an instance of the , hinder __init__ To be called
D. Called when a new instance is created __new, To initialize an instance __init
3、 ... and 、 Completion (5 branch 5 topic )
26. stay Python 2.7 in , After executing the following statements , Show what the results are ? answer :0 0.5
from future importdivision
print 1//2, 1/2
27. stay Python 2.7 in , What is displayed after executing the following statement ? answer :none 0
a = 1
b = 2 * a / 4
a = “none”
print a,b
28. What is the result of the execution of the following statements ? answer :[1, 2, 3, 1, 2, 3, 1, 2, 3]
a = [1, 2, 3]
print a3
29. What is the result of the execution of the following statements ? answer :3
a = 1
for i in range(5):
if i == 2:
break
a += 1
else:
a += 1
print a
30. What is the result of the following code ? answer :4
def bar(n):
m = n
while True:
m += 1
yield m
b = bar(3)
print b.next()

appendix :Python A selection of common interview questions
One 、 Basic knowledge of (7 topic )
topic 01:Python What do immutable data types and variable data types mean in ?
difficulty : *****【 Refer to the answer 】
Immutable data type means that the value of a variable is not allowed to change , If you change the value of a variable , So I created a new object , And for objects of the same value , There is only one object in memory ( An address ). Numerical type 、 character string string And a tuple tuple Are immutable data types .
A variable data type is one that allows the value of a variable to change , That is, if you execute append、+= Wait for the operation , Only the value of the variable will be changed , Instead of creating a new object , The address of the object referenced by the variable does not change . But for different objects with the same value , There will be different objects in memory , That is, each object has its own address , It's equivalent to saving multiple copies of the same value objects in memory , There is no reference count , It's a real object . list list And the dictionary dict All belong to variable data types .
topic 02: Please briefly Python in is and == The difference between .
difficulty :***** 【 Refer to the answer 】
Python The object in contains three elements :id、type and value.is The comparison is between two objects id.== The comparison is between two objects value.
topic 03: Please briefly function(args, **kwargs) Medium args, kwargs What do you mean by the difference ?
difficulty :***** 【 Refer to the answer 】
*args and kwargs It is mainly used for the parameters of function definition .Python Language allows you to pass an indefinite number of parameters to a function , among args Represents a list of variable parameters that are not key value pairs ,kwargs It indicates an indefinite number of key value pairs in the parameter list . Be careful :*args and kwargs It can also be used in the definition of a function , however args Must be in **kwargs front .
topic 04: Please briefly describe... In object-oriented __new__ and __init__ The difference between .
difficulty : *****【 Refer to the answer 】
(1)__new__ At least one parameter cls, Represents the current class , This parameter is instantiated by Python The interpreter automatically recognizes .

            (2) __new__ Returns the generated instance , You can return the parent class ( adopt super( The name of the class , cls) The way )__new__ The examples come out ,
1
Or directly to the object __new__ The examples come out . This is implemented in their own programming __new__ We should pay special attention to it .
(3) __init__ There is a parameter self, This is this. __new__ The returned instance ,__init__ stay __new__ Can complete a
Some other initialization actions ,init__ You don't need to return a value .
(4) If __new__ Create an instance of the current class , Automatically called __init, By returning the... Called in the statement __new__ Letter
The first argument to the number is cls To ensure that it is the current class instance , If it's the class name of another class , Then what is actually created and returned is instances of other classes , It will not call the current class or other classes __init__ function .
topic 05:Python When a subclass inherits from more than one parent class , If multiple parent classes have methods with the same name , Which method the subclass will inherit from ?
difficulty :*****

             【 Refer to the answer 】 
1
Python The method of language subclass inheriting the parent class is determined according to the sequence of inherited parent classes , for example , Subclass A Inherited from the parent class B、C, And B、C Method with the same name in Test(), that A Medium Test() Methods are actually inherited from B Medium Test() Method .
topic 06: Please briefly Python How to avoid deadlock in ?
difficulty :*****

             【 Refer to the answer 】 
1
Deadlock means that different threads acquire different locks , But threads want to get each other's lock , Both sides are waiting for each other to release the lock , This situation of waiting for resources is deadlock .Python Language can be used threading.Condition object , Coordinate the operation of threads in the form of conditional event notification , To avoid deadlock .
topic 07: What is the stability of sorting algorithm ? Common sorting algorithms, such as bubble sorting 、 Quick sort 、 Merge sort 、 Stack row
order 、Shell Sort 、 Binary tree sorting, etc 、 Space complexity and stability ?
difficulty :*****

             【 Refer to the answer 】 
1
Assume in the sequence of records to be sorted , There are multiple records with the same keyword , If sorted , The relative order of these records remains the same , In the original sequence ,r[i]=r[j], And r[i] stay r[j] Before , In the sorted sequence ,r[i] Still in r[j] Before , We call this sort algorithm stable ; Otherwise it is called unstable .
The time of common sorting algorithms 、 The space complexity and stability are shown in the following table .


* In the complexity of cardinality sorting ,r Represents the cardinality of the keyword ,d Length ,n Indicates the number of keywords .

Two 、 Strings and numbers (7 topic )
topic 08: The string contents are de duplicated and arranged alphabetically .
difficulty :*****
Make s = “hfkfdlsahfgdiuanvzx”, Try to be right s De duplication and output in alphabetical order “adfghiklnsuvxz”.
【 Refer to the answer 】

s = "hfkfdlsahfgdiuanvzx" 
s = list(set(s)) s.sort(reverse=False) print("".join(s))


1
2
3
4
topic 09: Determine whether two strings are isomorphic .
difficulty :*****
String isomorphism refers to string s All characters in can be replaced with t All characters in . While preserving the character order , All characters that appear must be replaced with another character . Can't be s Two characters in are mapped to t The same character in , But characters can map to themselves . Try to determine the given string s and t Is it isomorphic . for example : s = “add” t = “apple” Output False s = “paper” t = “title”
Output
True 【 Refer to the answer 】

print(len(set(s)) == len(set(t)) == len(set(zip(s, t))))

1
2
topic 10: Use Lambda The expression implementation will IPv4 The address of int Type integer .
difficulty :*****
for example :ip2int(“192.168.3.5”) Output :
3232236293

【 Refer to the answer 】


ip2int = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) 
1
2
topic 11: Roman numerals use letters to represent specific numbers , Try to write a function romanToInt(), Enter Roman numeric characters
strand , Output the corresponding Arabic numerals .
difficulty :*****

【 Refer to the answer 】
The correspondence between letters and Arabic numerals in Roman numerals is as follows :
M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL: 40,X:10,IX:9,V:5,VI:4,I:1

   def romanToInt(s): 
    table = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL': 40, 'X':10, 'IX':9, 'V':5, 'VI':4, 'I':1}     result = 0 
    for i in range(len(s)): 
        if i > 0 and table[s[i]] > table[s[i-1]]:             result += table[s[i]]             result -= 2 * table[s[i-1]]         else: 
            result += table[s[i]]     return result 
1
2
3
4
5
topic 12: Determine whether the brackets are paired .
difficulty :*****
Given a string containing only characters “(”“)”“{”“}”“[” and “]” String , Try to write a function isParenthesesValid(), Enter the string , Determines whether the entered string is valid . Parentheses must be closed in the correct order , for example “()” and “()[]{}” It's all valid , but “(]” and “([]]” No .
【 Refer to the answer 】

 def isParenthesesValid(s):     pars = [None] 
    parmap = {')': '(', '}': '{', ']': '['}     for c in s: 
        if c in parmap: 
            if parmap[c] != pars.pop():                 return False         else: 
            pars.append(c)     return len(pars) == 1 
1
2
3
4
5
topic 13: Write function output count-and-say The first of the sequence n term .
difficulty :*****
count-and-say A sequence is a sequence of integers , The first five elements are as follows : 1 11 21

            1211 111221 
1
1 pronounce as “1” or 11.11 pronounce as “ Two 1” or 21.21 pronounce as “ One 2, Then one 1” or 1211. That is, the next item is the previous item “ Read it out ” Then write it in numbers .
Try to write a function CountAndSay(n), Output count-and-say The first of the sequence n term . 【 Refer to the answer 】


                def CountAndSay(n):     ans = "1"     n -= 1     while n > 0:         res = ""         pre = ans[0]         count = 1 
        for i in range(1, len(ans)):             if pre == ans[i]:                 count += 1             else: 
                res += str(count) + pre                 pre = ans[i]                 count = 1         res += str(count) + pre         ans = res 

         
                        n -= 1     return ans 
1
2
3
4
5
6
7
topic 14: Don't use sqrt

            function , Trial compilation squareRoot() function , Enter a positive number , Output the integer of its square root
1
Several parts
difficulty :***** 【 Refer to the answer 】

  def squareRoot(x):     result = 1.0 
                    while abs(result * result - x) > 0.1:         result = (result + x / result) / 2 
                    return int(result) 
1
2
3
3、 ... and 、 Regular expressions (4 topic )
topic 15: Please write out the mobile phone number Chinese mainland and end it is not 4 and 7 Regular expression of .
difficulty :***** 【 Refer to the answer 】

            import re 
1
tels = [“159********”, “14456781234”, “12345678987”, “11444777”] for tel in tels:
print(“Valid”) if (re.match(r"1\d{9}[0-3,5-6,8-9]", tel) != None) else print(“Invalid”)
topic 16: Write the result of the following code .
difficulty :*****

 import re 

  str = '<div class="nam"> China </div>' 
res = re.findall(r'<div class=".*">(.*?)</div>',str) print(res) 
1
2
3
4
            give the result as follows : 【 Refer to the answer 】 
1
[' China ']
topic 17: Write the result of the following code .
difficulty :*****

import re 

                match = re.compile('www\....?').match("www.baidu.com") if match: 
    print(match.group()) else:                                
                    print("NO MATCH") 
1
2
3
4
5
【 Refer to the answer 】
www.bai
topic 18: Write the result of the following code .
difficulty :*****

 import re  
example = "<div>test1</div><div>test2</div>" Result = re.compile("<div>.*").search(example) 
      
                print("Result = %s" % Result.group()) 
1
2
3
4
【 Refer to the answer 】
Result =

test1
test2
            Four 、 list 、 Dictionaries 、 Tuples 、 Array 、 matrix (9 topic ) 
1
topic 19: The matrix is transformed into a one-dimensional vector by recursion .
difficulty :***** Use recursion to [[ 1, 2 ], [ 3, 4 ], [ 5, 6 ]]
Convert to

             [1, 2, 3, 4, 5, 6]. 【 Refer to the answer 】 
            a = [[1, 2], [3, 4], [5, 6]] print([j for i in a for j in i]) 
1
2
topic 20: Write the running results of the following code .
difficulty :*****

def testFun():  

                    temp = [lambda x : i*x for i in range(5)]  
            
                
            
                    return temp 
for everyLambda in testFun():      print (everyLambda(3)) 
1
2
3
4
5
6
7
8
give the result as follows : 【 Refer to the answer 】

            12 12 12 12 12 
1
topic 21: To write Python Program , Print the asterisk pyramid .
difficulty :*****
Write as short as possible Python Program , Realize printing asterisk pyramid . for example n=5 Output the following pyramid graphics :

                 * 
        
            
        
                ***    *****   *******  ********* 
1
2
3
4
5
The reference codes are as follows : 【 Refer to the answer 】

                n = 5 
for i in range(1,n+1): 
    print(' '*(n-(i-1))+'*'*(2*i-1)) 
1
2
3
topic 22: Get the dominant point of the array .
difficulty :*****
Dominant number refers to the dominant number when the number of occurrences of an element in the array is greater than half of the total number of array elements , Its subscript is called the dominant point . To write Python

            function FindPivot(li), Input array , Output the dominating point and dominating number , If there is no dominant number in the array , Output None. 
1
for example :[3,3,1,2,2,1,2,2,4,2,2,1,2,3,2,2,2,2,2,4,1,3,3] The Communist Party of China has 23 Elements , The elements 2 There is 12 Time , The combination of dominating point and dominating number is (18, 2). 【 Refer to the answer 】

  def FindPivot(li):     mid = len(li)/2     for l in li:         count = 0         i = 0         mark = 0         while True:             if l == li[i]:                 count += 1                 temp = i             i += 1 
            if count > mid:                 mark = temp 
                return (mark, li[mark])             if i > len(li) - 1:                 break 
1
2
3
topic 23: Sort the functions according to their execution efficiency
difficulty :*****
There are three functions , Please sort them according to execution efficiency .

  def S1(L_in): 
    l1 = sorted(L_in) 
    l2 = [i for i in l1 if i<0.5]     return [i*i for i in l2]  

            
                
            
                def S2(L_in): 
    l1 = [i for i in L_in if i<0.5]     l2 = sorted(l1) 
    return [i*i for i in l2]  
def S3(L_in): 
    l1 = [i*i for i in L_in]     l2 = sorted(l1) 
    return [i for i in l2 if i<(0.5*0.5)] 
1
2
3
4
5
6
7
8
9
10
11
12
13
【 Refer to the answer 】
Use cProfile The library can test the execution efficiency of three functions :

import random import cProfile  
L_in = [random.random() for i in range(1000000)] 
                cProfile.run('S1(L_in)') cProfile.run('S2(L_in)') cProfile.run('S3(L_in)') 
1
2
3
From the results, we can see , The order of execution efficiency from high to low is S2、S1、S3.
topic 24: Spiral returns the elements of the matrix
difficulty :*****
Given m×n A matrix of elements (m That's ok ,n Column ), To write Python

            function spiralOrder(matrix), Returns all elements of the matrix in spiral order . 
1
for example , Given the following matrix : [[ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
Should return to [1,2,3,6,9,8,7,4,5]
【 Refer to the answer 】

   def spiralOrder(matrix): 
    if len(matrix) == 0 or len(matrix[0]) == 0:         return []     ans = [] 
    left, up, down, right = 0, 0, len(matrix) - 1, len(matrix[0]) - 1     while left <= right and up <= down:         for i in range(left, right + 1):             ans += matrix[up][i],         up += 1 
        for i in range(up, down + 1):             ans += matrix[i][right],         right -= 1 
        for i in reversed(range(left, right + 1)):             ans += matrix[down][i],         down -= 1 
        for i in reversed(range(up, down + 1)):             ans += matrix[i][left],         left += 1 
    return ans[:(len(matrix) * len(matrix[0]))] 
1
2
3
4
5
6
7
topic 25: Matrix renormalization
difficulty :*****

            For a given two-dimensional array representation of the matrix , And two positive integers r and c, Respectively represent the number of rows and columns of the matrix to be reshaped .reshape Function to generate a new matrix , And all elements of the original matrix are filled in in the same row traversal order as the original matrix , Reshape the matrix into a matrix of different sizes, but retain its original data . For a given matrix and parameter reshape The operation can be completed and legal , Then output a new matrix ; otherwise , Output raw matrix . Please use Python Language implementation reshape function . for example : 

        
            
        
            Input  
1
2
3
4
5
6
r, c Output

explain

nums = [[1,2], [3,4]] r = 1,c =
4 [[1,2,3,4]]
Row traversal is [1,2,3,4]. The new reshaping matrix is 1 * 4 matrix , Fill line by line with the previous list .
nums = [[1,2], [3,4]]
r = 2,c =
4
[[1,2], [3,4]]
Cannot be 2 * 2 Reshape the matrix to 2 * 4 matrix . So output the original matrix .
Be careful : The height and width of a given matrix are [1,100] Within the scope of . A given r and c All positive numbers. .
【 Refer to the answer 】

def matrixReshape(nums, r, c):     """ 
    if r * c != len(nums) * len(nums[0]):         return nums     m = len(nums)     n = len(nums[0]) 
    ans = [[0] * c for _ in range(r)]     for i in range(r * c): 
        ans[i / c][i % c] = nums[i / n][i % n]     return ans 
1
2
3
4
topic 26: Find the... In the matrix k The smallest element .
difficulty :*****
Given n×n matrix , The elements in each row and column are arranged in ascending order , Trial compilation Python function kthSmallest(matrix, k), Find the... In the matrix k The smallest element .
Be careful : The search is the... In the sort order k The smallest element , Not the first. k Different elements . for example : matrix = [[1,5,9], [10,11,13], [12,13,15]] k = 8, Should return 13.

            【 Refer to the answer 】 
1
 import heapq  
def kthSmallest(matrix, k):     visited = {(0, 0)} 
    heap = [(matrix[0][0], (0, 0))] 
                
    while heap: 
        val, (i, j) = heapq.heappop(heap)         k -= 1         if k == 0:             return val 
                    if i + 1 < len(matrix) and (i + 1, j) not in visited: 
   
                            heapq.heappush(heap, (matrix[i + 1][j], (i + 1, j)))             visited.add((i + 1, j)) 
        if j + 1 < len(matrix) and (i, j + 1) not in visited:             heapq.heappush(heap, (matrix[i][j + 1], (i, j + 1)))             visited.add((i, j + 1)) 
1
2
3
4
5
6
7
8
9
10
topic 27: Try to write a function largestRectangleArea(), Find the area of the largest rectangle contained in a histogram .
difficulty :***** For example, for the following figure :

Input :[2,1,5,6,2,3] Output :10
【 Refer to the answer 】

def largestRectangleArea(heights):     stack=[]     i=0     area=0 
    while i<len(heights): 

                        if stack==[] or heights[i]>heights[stack[len(stack)-1]]:  # Increment directly into the stack  
               stack.append(i)         else:  # Don't increment start bouncing stack             
                            curr=stack.pop()             if stack == []:                 width = i              else: 
                width = i-stack[len(stack)-1]-1             area=max(area,width*heights[curr])             i-=1         i+=1  
   while stack != []:         curr = stack.pop()         if stack == []:             width = i          else: 
            width = len(heights)-stack[len(stack)-1]-1         area = max(area,width*heights[curr])     return area 
1
2
3
4
5
6
7
8
9
5、 ... and 、 Design patterns (3

            topic ) 
1
topic 28: Use Python Language implements the singleton pattern .
difficulty :*****

【 Refer to the answer 】

class Singleton(object): 
    def __new__(cls, *args, **kw):         if not hasattr(cls, '_instance'):             orig = super(Singleton, cls) 
            cls._instance = orig.__new__(cls, *args, **kw)         return cls._instance 
1
2
3
topic 29: Use Python Language implementation factory pattern .
difficulty :*****
Write appropriate Python Program , Complete the following functions : 1. Define base class Person, Get the name , Gender approach . 2. Definition Person Two subclasses of class Male and Female, Contains a way to say hello . 3. Define factory class , contain getPerson Method , Accept two input parameters : Name and gender . 4. By calling getPerson Method uses factory class .
【 Refer to the answer 】

class Person: 
                    def __init__(self):         self.name = None         self.gender = None  
    def getName(self):         return self.name  
    def getGender(self):         return self.gender  
class Male(Person): 
    def __init__(self, name):         print("Hello Mr." + name)  
                class Female(Person): 
    def __init__(self, name):         print("Hello Miss." + name)  
class Factory: 
    def getPerson(self, name, gender):         if(gender == 'M'):             return Male(name)         if(gender == 'F'):             return Female(name)  
if __name__ == '__main__':     factory = Factory() 
    person = factory.getPerson("Huang", "M") 
1
2
3
4
5
6
7
8
9
10
11
12
topic 30: Use Python The language implements the observer pattern .
difficulty :*****
Given a number , The existing default formatted display program displays this number in decimal format . Please write the appropriate Python Program , The implementation supports adding ( register ) More formatter ( Such as adding a hexadecimal formatter and a binary formatter ). Every time the value is updated , Registered programs will be notified , And display the updated value .
【 Refer to the answer 】

import itertools class Publisher:     def __init__(self):         self.observers = set()  
    def add(self, observer, *observers): 
        for observer in itertools.chain((observer, ), observers):             self.observers.add(observer) 
                            observer.update(self)  
    def remove(self, observer):         try: 
            self.observers.discard(observer)         except ValueError: 
            print(' remove {} Failure !'.format(observer))  
    def notify(self): 
        [observer.update(self) for observer in self.observers]  
class DefaultFormatter(Publisher):     def __init__(self, name):         Publisher.__init__(self)         self.name = name         self._data = 0  
    def __str__(self): 
        return "{}: '{}' Value = {}".format(type(self).__name__, self.name, self._data)  
    @property     def data(self):         return self._data  
    @data.setter 
    def data(self, new_value):         try: 
            self._data = int(new_value)         except ValueError as e:             print(' error : {}'.format(e))         else: 
            self.notify()  
class HexFormatter: 
    def update(self, publisher): 
        print("{}: '{}' The hexadecimal value of = {}".format(type(self).__name__, publisher.name, hex(publisher.data)))  
class BinaryFormatter: 
    def update(self, publisher): 
        print("{}: '{}' The binary value of = {}".format(type(self).__name__, publisher.name, bin(publisher.data)))  
def main(): 
    df = DefaultFormatter('test1')     print(df)                            
    hf = HexFormatter()           
                    df.add(hf)     df.data = 37     print(df)               
    bf = BinaryFormatter()     df.add(bf)     df.data = 23     print(df)  
    df.remove(hf)     df.data = 56     print(df)        
                    df.remove(hf)     df.add(bf)  
    df.data = 'hello'     print(df)  
    df.data = 7.2     print(df)  
if __name__ == '__main__':     main() 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
6、 ... and 、 Trees 、 Binary tree 、 chart (5 topic )
topic 31: Use Python Write a function to realize the preorder traversal of binary tree preorder(root, res=[]).
difficulty :***** 【 Refer to the answer 】

def preorder(root, res=[]):     if not root:         return  
    res.append(root.val)     preorder(root.left,res)     preorder(root.right,res)     return res 
1
2
topic 32: Use Python Implement a binary search function .
difficulty :*****

【 Refer to the answer 】

def binary_search(num_list, x):     num_list = sorted(num_list)     left, right = 0, len(num_list) - 1     while left <= right: 
                        mid = (left + right) // 2         if num_list[mid] > x:             right = mid - 1         elif num_list[mid] < x:             left = mid + 1         else: 
            return ' Elements to be checked {0} After sorting, the subscript in the list is :  
                {1}'.format(x, mid)     return ' Elements to be found %s Does not exist in the specified list ' %x 
topic
            
1
2
3
4
5
6
            33: To write Python function maxDepth(), Get binary tree root Maximum depth . 
1
difficulty :***** 【 Refer to the answer 】

def maxDepth(self, root):         if root == None:             return 0 
        return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 
1
2
topic 34: Input two binary trees Root1、Root2, Judge Root2 whether Root1 Substructure of ( subtree ).
difficulty :***** 【 Refer to the answer 】

class TreeNode: 
    def __init__(self, x):         self.val = x         self.left = None         self.right = None  
def istree(pRoot1, pRoot2):     if not pRoot2:         return True 
    if not pRoot1 and pRoot2:         return False 
    if pRoot1.val != pRoot2.val:         return False 
    elif pRoot1.val == pRoot2.val: 
        return istree(pRoot1.left, pRoot2.left) and istree(pRoot1.right, pRoot2.right) 
                 
def HasSubtree(pRoot1, pRoot2):     if not pRoot1 or not pRoot2:         return False       
                    if pRoot1.val == pRoot2.val:         return istree(pRoot1, pRoot2)     else: 
        return HasSubtree(pRoot1.left, pRoot2) or HasSubtree(pRoot1.right, pRoot2) 
1
2
3
4
5
6
7
8
9
10
11
topic 35: Determine whether the array is the result of post order traversal of a binary search tree .
difficulty :*****
Write function VerifySquenceOfBST(sequence), Implement the following functions : Enter an array of integers , Determine whether the array is the result of the subsequent traversal of a binary search tree . Output if yes True, Otherwise output False. Suppose that any two numbers of the input array are different from each other . 【 Refer to the answer 】

def VerifySquenceOfBST(sequence):     if not sequence: 
            
                
            
                        return False     i= 0 
    for i in range(len(sequence)-1): 
            
                
            
                        if sequence[i]>sequence[-1]:             break 
    if i < len(sequence)-2: 
        for j in range(i+1,len(sequence)-1):             if sequence[j]<sequence[-1]:                 return False     left = True     right = True     if i>0: 
        left = VerifySquenceOfBST(sequence[:i])     elif i< len(sequence)-2: 
        right = VerifySquenceOfBST(sequence[i:-1])     return left and right 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
7、 ... and 、 File operations (3 topic )
topic 36: Calculation test.txt The number of uppercase letters in .
difficulty :***** 【 Refer to the answer 】

import os os.chdir('D:\\') 
with open('test.txt') as test:     count = 0 
    for i in test.read():         if i.isupper():             count+=1 
         print(count) 
1
2
3
4
topic 37: Complete the missing code .
difficulty :*****
def print_directory_contents(sPath): # Supplement the implementation code of the function
print_directory_contents() The function takes a folder path name as an input parameter , Returns the full path of all subfolders and files contained in it .
【 Refer to the 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) 
1
2
3
4
5
topic 38: Design the file system in memory .
difficulty :*****
Use Python Language design file system in memory , Implement the following command .
ls: The path in the given string format . If it's a file path , Returns a list containing only the file name . If it is a directory path , Returns a list of file and directory names in this directory . Output results ( File and directory names ) It should be arranged in dictionary order .
mkdir: If the directory path does not exist , Then a new directory should be created according to the path . If the intermediate directory in the path does not exist , You should also create them . This function has void Return type . notes :
You can assume that all file or directory paths are / And don't start with / The absolute path to the end , Except that the path is just “/”. It can be assumed that all operations will pass valid parameters , Users do not attempt to retrieve file contents or list directories or files that do not exist . You can assume that all directory names and file names contain only lowercase letters , And the same name does not exist in the same directory .

【 Refer to the answer 】

  class FileNode(object):     def __init__(self, name):         self.isFolder = True         self.childs = {}         self.name = name         self.data = ""  
class FileSystem(object):     def __init__(self): 
        self.root = FileNode("/")  
    def ls(self, path): 
        fd = self.lookup(path, False)         if not fd:             return []         if not fd.isFolder:             return [fd.name]         files = [] 
        for file in fd.childs:             files.append(file)         files.sort()         return files  
    def lookup(self, path, isAutoCreate):         path = path.split("/")         p = self.root         for name in path:             if not name:                 continue 
            if name not in p.childs:                 if isAutoCreate: 
                    p.childs[name] = FileNode(name)                 else: 
                    return None             p = p.childs[name]         return p  
    def mkdir(self, path): 
        self.lookup(path, True)       # test  
obj = FileSystem() obj.mkdir("/test/path") obj.ls("/test") 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
            8、 ... and 、 Network programming (4 topic )
1
topic 39: Please say at least three TCP and UDP The difference between agreements .
difficulty :*****

【 Refer to the answer 】
(1) TCP Connection oriented ( If you want to make a call, dial to establish a connection );UDP It's disconnected , That is, there is no need to establish a connection before sending data
Pick up .
(2) TCP Provide reliable service . in other words , adopt TCP Connect the transmitted data , No mistakes , No loss , No repetition , And in order
arrive ;UDP Do your best to deliver , That is, there is no guarantee of reliable delivery .
(3) TCP Byte stream oriented , It's actually TCP Think of data as a stream of unstructured bytes ;UDP It's message oriented ,UDP no
There's congestion control , Therefore, the network congestion will not reduce the transmission rate of the source host ( Useful for real-time applications , Such as IP Telephone , Real time video conference, etc ).
(4) Every one of them TCP Connections can only be point-to-point ;UDP Support one-to-one , One to many , Many to one and many to many interactive communication . (5) TCP First cost 20 byte ;UDP The cost of the first part is small , Only 8 Bytes .
(6) TCP The logical communication channel of is a full duplex reliable channel ,UDP It's an unreliable channel .
topic 40: Please briefly Cookie and Session The difference between .
difficulty :*****

【 Refer to the answer 】
(1) Session On the server side ,Cookie On the client side ( browser ).
(2) Session Can be stored in a file 、 Database or memory , Save as a file by default . (3) Session It depends on Session ID, and Session ID Save in Cookie in . therefore , If the browser is disabled Cookie,
meanwhile Session It's going to fail .
topic 41: Please briefly describe how to send a request to the server GET Ways and POST Differences in methods .
difficulty :*****

【 Refer to the answer 】
(1) When the browser goes back GET The way has not changed , and POST The request will be submitted again . (2) GET Requests will be actively cached by the browser , and POST Can't , Unless manually set . (3) GET Request can only proceed URL code , and POST Supports a variety of coding methods .
(4) GET The request parameters are fully preserved in the browser history , and POST The parameters in are not retained . (5) The data type for the parameter ,GET We only accept ASCII character , and POST There is no limit to .
(6) GET Than POST It's not safe , Because the parameters are directly exposed to URL On , So it can't be used to convey sensitive information .
(7) GET Parameters through URL The parameters passed are limited in length ,POST Put it in Request body Medium and no length
Limit .
(8) about GET Method request , The browser will http header and data Send along , Server response 200( Return number
According to the ); And for POST, Browser sends first header, Server response 100 continue, The browser sends data, Server response 200 ok( Return the data ).

topic 42: Use threading Component writing supports multithreading Socket Server side .
difficulty :*****
Use Python Linguistic threading Component writing supports multithreading Socket Server side , Support -x and -p Parameters , Indicates the specified maximum number of connections and listening port respectively .

【 Refer to the answer 】

  import socket 
import threading,getopt,sys,string                  
opts, args = getopt.getopt(sys.argv[1:], "hp:l:",["help","port=","list="])  list=50 port=8001  
for op, value in opts: 
    if op in ("-x","--maxconn"):         list = int(value)     elif op in ("-p","--port"):         port = int(value)  
def Config(client, address):     try: 
        client.settimeout(500)         buf = client.recv(2048)         client.send(buf)     except socket.timeout:         print('time out')     client.close()  
def main(): 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     sock.bind(('localhost', port))     sock.listen(list)     while True: 
        client,address = sock.accept() 
        thread = threading.Thread(target=Config, args=(client, address))         thread.start()  
if __name__ == '__main__':     main() 
1
2
3
4
5
6
7
8
9
10
11
12
Nine 、 Database programming (6 topic )
topic 43: Briefly describe the first step of the database 、 second 、 The content of the third paradigm .

difficulty :*****

【 Refer to the answer 】
The paradigm is “ A set of relational patterns that conform to a certain level , Indicates the degree of rationalization of the relationship between attributes within a relationship ”, In fact, it is the level of some design standard that the table structure of a data table conforms to .
1NF For the definition of : accord with 1NF Each attribute in the relation of .1NF Is the most basic requirement of all relational databases . 2NF stay 1NF Based on , Partial function dependence of non - primary attributes on code is eliminated . The judgment steps are as follows . First step : Find all the codes in the data table .
The second step : According to the code obtained in the first step , Find out all the main properties .
The third step : In the data table , Remove all primary attributes , The rest are non primary attributes . Step four : Check whether there are partial functional dependencies of non primary attribute on code .
3NF stay 2NF Based on , The transfer function dependence of non-primary attributes on codes is eliminated .
topic 44: According to the following data table structure and data , Write as required SQL sentence .
difficulty :*****
Existing in database Course、Score、Student and Teacher Four data sheets , The data are as follows .

Trial compilation SQL sentence , Query average score greater than 80 Of all students 、 Name and average score .
【 Refer to the answer ( Use SQLServer)】

select a.s_id, b.s_name, avg(a.s_score) as avg_score from Score a, Student b where a.s_id=b.s_id group by a.s_id, b.s_name having avg(a.s_score)>80 
1
The query results are as follows :


topic 45: according to 44 The conditions given in the question , To write SQL Query the information of students who have not studied all courses .
difficulty :*****
【 Refer to the answer ( Use SQLServer)】

select b.s_id, b.s_name from Score a, Student b where a.s_id=b.s_id 
  group by b.s_id, b.s_name 
having count(a.c_id)<(select count(c_id) from Course) 
1
2
3
The query results are as follows :


topic 46: according to 44 The conditions given in the question , To write SQL Sentence to query all courses 2

            Name and number 3 Student information and the course
1
Cheng achievement .
difficulty :*****
【 Refer to the answer ( Use SQLServer)】

  select * from ( 
select a.s_id, b.s_name, b.s_birth, b.s_sex, a.c_id, a.s_score, row_number() over (partition by a.c_id order by a.s_score desc) rno from Score a, Student b where a.s_id=b.s_id 
    ) as a where a.rno in (2, 3) order by c_id, rno 
1
2
3
The query results are as follows :


topic 47: according to 44 The conditions given in the question , To write SQL The courses taught by sentence query are 2 Teachers who fail at or above 、 course
cheng 、 Student information and course results .
difficulty :*****

            【 Refer to the answer ( Use SQLServer)】 
1
  select a.s_id, d.s_name, a.s_score, a.c_id, b.c_name, b.t_id, c.t_name from Score a, Course b, Teacher c, Student d 
where a.c_id=b.c_id and b.t_id=c.t_id and a.s_id=d.s_id and a.s_score<60 and c.t_id in (  SELECT c.t_id   
                 FROM Score a, Course b, Teacher c 
 where a.c_id=b.c_id and b.t_id=c.t_id and a.s_score<60  group by c.t_id  having count(1)>1 

1
2
3
4
5
The query results are as follows :


topic 48: according to 44 The conditions given in the question , To write SQL Statement to generate a segmented table for each course ( Course ID、 Course name
call 、 fraction 、 The number of people in this course 、 The cumulative number of people in this course ).

            difficulty :*****
1
【 Refer to the answer ( Use SQLServer)】

select a.c_id, b.c_name, a.s_score, COUNT(1) The number of , 
(select COUNT(1) from Score c where c.c_id=a.c_id and c.s_score>=a.s_score) Cumulative number of people from Score a, Course b where a.c_id=b.c_id 
group by a.c_id, b.c_name, a.s_score order by a.c_id, b.c_name, a.s_score desc; 
1
2
3
The query results are as follows :


Ten 、 Graphics and visualization (2 topic )

topic 49: Draw a graph of a quadratic function , At the same time, each trapezoid when using the trapezoid method to calculate the integral is drawn .
difficulty :*****

             【 Refer to the answer 】 
1
With 𝑓(𝑥)=6𝑥2+7𝑥+13 For example , The code is as follows :

  def Quadratic_Function(x): 

                    return 6*x**2 + 7*x + 13  
import numpy as np 
import matplotlib.pyplot as plt from ipywidgets import interact  
def plot_ladder(laddernum): 
    x = np.linspace(-5, 5, num=100)     y = Quadratic_Function(x)     plt.plot(x, y)      
    a = np.linspace(-5, 5, num=laddernum)     for i in range(laddernum): 
        plt.plot([a[i], a[i]], [0, Quadratic_Function(a[i])], color="blue")  
    ladders = [] 
                    for i in range(laddernum): 
        ladders.append([a[i], Quadratic_Function(a[i])])      
    npladders = np.array(ladders) 
    plt.plot(npladders[:,0], npladders[:,1])  
interact(plot_ladder, laddernum=(1, 80, 1)) 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The operation results are as follows ( Use Jupyter Notebook):


topic 50: Visualize the given data and give the analysis conclusion
difficulty :*****
The age of some customers in a store 、 The monthly income and average monthly consumption in our store are shown in the table below .


Please use... Accordingly Python Language draw appropriate graphics and analyze them to get conclusions . 【 Refer to the answer 】

import matplotlib.pyplot as plt plt.figure(figsize=(10, 5)) # Age  
age = [34, 40, 37, 30, 44, 36, 32, 26, 32, 36] # income  
income = [7000, 9000, 3380, 3780, 3660, 1600, 3320, 2400, 1500, 2800] # Consumption  
expense = [1230, 1140, 1350, 1390, 1170, 1210, 1330, 1400, 1330, 1330] # Age , income Scatter plot ax1 = plt.subplot(121) ax1.scatter(age, income) 
ax1.set_title(' Age , income Scatter plot ', family='kaiti', size=16) # Age , Consumption Scatter plot ax2 = plt.subplot(122) ax2.scatter(age, expense) 
ax2.set_title(' Age , Consumption Scatter plot ', family='kaiti', size=16) plt.show() 
1
2
3
4
5
6


As you can see from the diagram , Customer age is almost negatively correlated with consumption , Income and consumption are also almost negatively correlated , There is no obvious correlation between age and income .

140. Yes Flask The blueprint (Blueprint) The understanding of the ?
Definition of blueprint
The blueprint /Blueprint yes Flask The method of application componentization , Blueprints can be shared within an application or across multiple projects . Using blueprints can greatly simplify the difficulty of developing large applications , Also for the Flask Extension provides a centralized mechanism for registering services in applications . Application scenario of blueprint :
Decompose an application into a collection of blueprints . This is ideal for large applications . A project can instantiate an application object , Initialize several extensions , And register a set of blueprints .
With URL The prefix and / Or subdomain , Register a blueprint on the application .URL Prefix / The parameters in the subdomain name become the common view parameters of all view functions under this blueprint ( By default ) Use different ones in an application URL The rule registers a blueprint multiple times .
Provide template filters through blueprints 、 Static files 、 Templates and other functions . A blueprint does not have to implement application or view functions .
Initialize a Flask When expanding , In these cases, register a blueprint . The shortcomings of the blueprint :
You cannot unregister a blueprint after an application is created without destroying the entire application object . The three steps of using the blueprint 1. Create a blueprint object
blue = Blueprint(“blue”,name)
2. Operate on this blueprint object , For example, register routing 、 Specify a static folder 、 Register template filters …
@blue.route(‘/’) def blue_index():
return “Welcome to my blueprint”
3. Register the blueprint object on the application object

            app.register_blueprint(blue,url_prefix="/blue") 
1
141.Flask and Django The difference between routing mapping ?

            stay django in , Routing is when the browser accesses the server , In the project accessed first url, And then by the url Find... In the application url, these url It's on a list , Follow the rules of matching from front to back . stay flask in , Routing is provided to each view function through the decorator , And according to different request methods, you can one url For different purposes . 
1
Django
142. What is? wsgi,uwsgi,uWSGI?
WSGI:
web Server gateway interface , It's a set of agreements . Used to receive user requests and encapsulate them for the first time , Then give the request to web frame .
Realization wsgi Protocol module :wsgiref, It's essentially writing a socket Server side , Used to receive user requests (django)
werkzeug, It's essentially writing a socket Server side , Used to receive user requests (flask) uwsgi:
And WSGI It's also a communication protocol , It is uWSGI Exclusive protocol for the server , Used to define the type of transmission information . uWSGI:
It's a web The server , Realized WSGI The agreement ,uWSGI agreement ,http agreement
143.Django、Flask、Tornado Comparison of ?
1、 Django Go in a big and comprehensive direction , High development efficiency . its MTV frame , Self contained
ORM,admin Background management , Self contained sqlite Server for database and development testing , Improve the development efficiency of developers . heavyweight web frame , The function is all ready , Provide a one-stop solution , So that developers don't have to spend a lot of time on choice .
Bring their own ORM And template engine , Support jinja Wait for the unofficial template engine .
Bring their own ORM send Django High coupling with relational database , If you want to use a non relational database , Third party libraries are needed Self contained database management app mature , Stable , High development efficiency , be relative to Flask,Django The overall closeness of , It is suitable for the development of enterprise websites .python web The forerunner of the framework , The third party library is rich
2、 Flask It's a lightweight framework , free , flexible , High scalability , Core based Werkzeug WSGI Tools and jinja2 template engine
Suitable for small websites and web Service API, There is no pressure to develop large websites , But the architecture needs to be designed
The combination with relational database is not weaker than Django, And the combination with non relational database is far better than Django
3、 Tornado It's a small and precise way to go , Superior performance , Its most famous asynchronous non blocking design
Tornado Two core modules of :
iostraem: For non blocking socket Simple encapsulation ioloop: Yes I/O Multiplex packaging , It implements a singleton
144.CORS and CSRF The difference between ?
What is? CORS?
CORS It's a W3C standard , The full name is “ Cross-domain resource sharing "(Cross-origin resoure sharing). It allows the browser to cross to the source server , issue XMLHttpRequest request , Thus, the customer service AJAX A restriction that can only be used with the same origin . What is? CSRF?
CSRF The mainstream defense method is to generate a string of random forms when generating forms at the back end token, Built into the form as a field , meanwhile , Put this string token Implantation session in . Each time the form is submitted to the back end, the two values are checked for consistency , To determine whether the form submission is credible , After submitting it once , If this page is not generated CSRF token, that token Will be emptied , If there is a new need , that token Will be updated . The attacker can forge POST Form submission , But he doesn't have back-end built-in forms token,session There is no token To no avail .
145.Session,Cookie,JWT The understanding of the
Why use session management
as everyone knows ,HTTP A protocol is a stateless protocol , That is, each request is an independent request , There is no relationship between requests . But in the actual application scenario , This approach does not meet our needs . Take an example that everyone likes to use , Add items to the shopping cart , Consider this request alone , The server doesn't know whose product it is , Whose shopping cart should be added ? Therefore, the context of this request should actually contain information about the user , Put this... Every time the user makes a request A small amount of additional information , As part of the request , In this way, the server can according to the information in the context , Operate for specific users . So the emergence of these technologies is right HTTP A supplement to the agreement , So that we can use HTTP agreement + State management builds a user oriented system WEB application .
Session and Cookie The difference between
Here I want to talk about session And cookies, Because these two technologies are the most common for development . that session And cookies What's the difference ? Personally think that session And cookies The core difference is who maintains the additional information . utilize cookies To implement session management , User related information or other information we want to keep in each request , It's all in cookies in , and
cookies Is saved by the client , Whenever a client makes a new request , Will take a little cookies, The server will operate according to the information . When using session For session management , The client actually saves only one message sent by the server session_id, And by this session_id, You can restore all the required state information on the server , It can be seen from here that this part of information is maintained by the server .
in addition to ,session And cookies They all have their own shortcomings : cookies It's not very safe , An attacker can obtain local information by cookies To deceive or take advantage of cookies Conduct CSRF attack . Use cookies when , Under multiple domain names , There will be cross domain problems . session In a certain time , It needs to be stored on the server , So when you have a large number of users , It will also greatly reduce the performance of the server , When there are multiple machines , How to share session It will also be a problem .(redis colony ) in other words , The first time a user visits is the server A, The second request is forwarded to the server B, The server B How to know its status . actually ,session And cookies It's connected , For example, we can put session_id Store in cookies Medium . JWT How it works
First, the user sends a login request , The server matches according to the user's login request , If the match is successful , Put relevant information into payload in , Using algorithms , Add the key generation of the server
token, What needs to be noted here is secret_key Very important , If this leaks , The client can randomly tamper with the additional information sent , It is the guarantee of information integrity . Generate token After that, the server returns it to the client , The client can , take token Give it to the server together , Generally speaking, we can put it in Authorization In the head , In this way, cross domain problems can be avoided .
146. sketch Django Request lifecycle
Generally, the user sends a request to our server through the browser (request), This request will access the view function , If there is no data call involved , At this time, the view function returns a template, that is, a web page to the user ) The view function calls the gross model to find data in the database , Then step back to , The view function fills the returned data into the space in the template , Finally return the web page to the user . 1.wsgi , Request sealed and handed over to web frame (Flask,Django)
2. middleware , Verify the request or add other relevant data to the request object , for example :csrf,request.session
3. Route matching Depending on the browser url To match different view functions 4. The view function , Processing business logic in view function , May involve :orm,templates
5. middleware , Process the response data 6.wsgi, Send the content of the response to the browser
147. With restframework complete api Send time zone
The current problem is to use django Of rest framework The module makes a get The sending time of the request and the time zone information api

class getCurrenttime(APIView):    def get(self,request): 
       local_time = time.localtime() 
       time_zone =settings.TIME_ZONE 
       temp = {'localtime':local_time,'timezone':time_zone}        return Response(temp) 
1
2
3
4
148.nginx,tomcat,apach What is it all about ?
Nginx(engine x) Is a high-performance HTTP And reverse proxy , It's also One IMAP/POP3/SMTP The server , Working in OSI Seven layers , Implementation of load : polling ,
IP_HASH,fair,session_sticky. Apache HTTP Server Is a modular server , From the NCSAhttpd The server Tomcat The server is a free open source Web application server , Application servers are lightweight , Is development and debugging JSP Program preference .
149. Please describe what relational database paradigms you are familiar with , What's the role ?
When designing the database , Some of the specifications followed , As long as the design is carried out in accordance with the design specifications , We can design a database structure without data redundancy and abnormal data maintenance .
There are many specifications for database design , Generally speaking, when we set up a database, we only need to meet some of these specifications , These specifications are also called the three paradigms of database , There are three , There are other paradigms , We just need to meet the requirements of the first three paradigms , We can set up a database that meets our requirements , We can't do it all according to the requirements of the paradigm , Also consider the actual business usage , So sometimes we need to do something against the paradigm . 1. The first paradigm of database design ( The most basic ), Basically, all database paradigms conform to the first paradigm , The table conforming to the first paradigm has the following characteristics :
All fields in the database table have only a single attribute , Single attribute columns are composed of basic data types ( integer , floating-point , Character type, etc ) The designed tables are simple binary tables 2. The second paradigm of database design ( It is designed on the basis of the first paradigm ), Only one business primary key is required in a table , In other words, a table that conforms to the second normal form cannot have a dependency relationship between non primary key columns and only partial primary keys
3. The third paradigm of database design , It means that each non primary attribute is neither partially dependent nor transitively dependent on the business primary key , That is, based on the second normal form, it eliminates the transfer dependence of non primary attributes on primary keys
150. sketch QQ Landing process
qq Sign in , There are three interfaces in our project ,
The first interface is the request qq The server returns a qq Login interface ;
The second interface is to verify through code scanning or account login ,qq The server returns a message to the browser code and state, Use this code Go to... Through the local server qq Server acquisition
access_token The override is returned to the local server , rely on access_token Again to qq The server gets the name of the user openid(openid The unique identification of the user )
The third interface is to determine whether the user is the first time qq Sign in , If not, log in directly and return jwt-token To the user , For users who have not been bound to this website , Yes openid Encryption generation token Binding
151.post and get The difference between ?
1.GET Get data from the server ,POST Is to send data to the server
2. On the client side ,GET The way is through URL Submit data , The data is in URL Can be seen in ,POST The way , The data is placed in HTML——HEADER The submission
3. about GET The way , Server side Request.QueryString Get the value of the variable , about POST The way , Server side Request.Form Get submitted data
152. The role of logs in the project
One 、 Log related concepts
1. Logging is a way to track events that occur while some software is running
2. Software developers can invoke log related methods in their code to show that something has happened
3. An event can be described by a message containing optional variable data
4. Besides , Events also have the concept of importance , This importance can also be called severity level (level) Two 、 The role of logs
1. adopt log Analysis of , It is convenient for users to understand the system or software 、 The operation of the application ; 2. If your app log Rich enough , It can analyze the operation behavior of previous users 、 Type preference , Geographical distribution or other more information ;
3. If an application log At the same time, it is also divided into multiple levels , Then the health status of the application can be easily analyzed , Find problems in time and locate them quickly 、 solve the problem , Remedy the loss .
4. In short, we can know whether a system or software program is running normally by recording and analyzing logs , You can also quickly locate problems when an application fails . Not only in development , Logs are also important in operation and maintenance , The role of logs can also be simple . It can be summarized as follows : 1. Program debugging
2. Understand the operation of software programs , If there is something wrong 3, Software program running fault analysis and problem location
4, If the application log information is sufficiently detailed and rich , It can also be used for user behavior analysis
153.django Use of middleware ?
Django Six methods are preset in the middleware , The difference between these six methods is that they are executed in different stages , To intervene in an input or output , The method is as follows :
1. initialization : No parameters required , Called once when the server responds to the first request , Used to determine if the current middleware is enabled
def init(): pass
2. Before processing the request : Call... On each request , return None or HttpResponse object .
def process_request(request): pass
3. Before working with views : Call... On each request , return None or HttpResponse object .
def process_view(request,view_func,view_args,view_kwargs): pass
4. Before processing the template response : Call... On each request , Back to implementation render Method .
def process_template_response(request,response): pass
5. After processing the response : All responses are called before returning to the browser , Call... On each request , return HttpResponse object . def process_response(request,response): pass
6. exception handling : Called when the view throws an exception , Call... On each request , Return to one HttpResponse object .
def process_exception(request,exception): pass
154. Talk about you being right uWSGI and nginx The understanding of the ?
1.uWSGI It's a Web The server , It has achieved WSGI agreement 、uwsgi、http Such agreement .Nginx in HttpUwsgiModule Its function is to communicate with uWSGI The server exchanges .WSGI It's a kind of Web Server gateway interface . It's a Web The server ( Such as nginx,uWSGI Wait for the server ) And web application ( If used Flask The program written by the framework ) A specification of communication . it is to be noted that WSGI/uwsgi/uWSGI The distinction between these three concepts . WSGI Is a communication protocol .
uwsgi It's a line protocol, not a communication protocol , This is often used in uWSGI Data communication between server and other network servers .
uWSGI Is to implement the uwsgi and WSGI Two kinds of agreement Web The server . nginx Is an open source high-performance HTTP Servers and reverse agents : 1. As web The server , It handles static files and index files very effectively
2. Its design pays great attention to efficiency , The biggest support 5 Million concurrent connections , But it only takes up very little memory space
3. High stability , Simple configuration .
4. Powerful reverse proxy and load balancing functions , Balance the load pressure of each server in the cluster
155.Python The application scenarios of the three frameworks in ?
django: It is mainly used for rapid development , His highlight is rapid development , Cost savings ,, If you want to achieve high concurrency , on django Secondary development , For example, take down the whole heavy frame and write it yourself socket Realization http Communication for , The bottom layer is made of pure c,c++ Writing improves efficiency ,ORM Get rid of the frame , Write your own framework to encapsulate the interaction with the database ,ORM Although object-oriented to operate the database , But it's inefficient , Use foreign keys to connect queries between tables ; flask: Lightweight , It's mainly a framework for writing interfaces , Achieve front and rear end separation , Improve development efficiency ,Flask Itself is equivalent to a kernel , Almost all other functions need to be extended ( Mail extension Flask-Mail, User authentication Flask-Login), All need to be implemented with third-party extensions . For example, you can use Flask-extension Join in ORM、 Upload files 、 Authentication, etc .Flask No default database , You can choose MySQL, It can also be used. NoSQL.
Its WSGI The tool box is used for Werkzeug( Routing module ), The template engine uses Jinja2, These two are also Flask The core of the framework .
Tornado: Tornado It's a kind of Web Open source version of server software .Tornado And now the mainstream Web Server framework ( Including most Python Framework ) There is a clear difference : It's a non blocking server , And it's pretty fast . Benefit from its non blocking way and to epoll The use of ,Tornado Thousands of connections can be processed per second, so Tornado It's real time Web An ideal framework for services
156.Django Where threads are used in ? Where is the synergy used ? Where processes are used ?
1.Django The time-consuming tasks in are executed by a process or thread , E-mail , Use celery. 2. Deploy django The project is time , The configuration file sets the related configuration of processes and processes .
157. used Django REST framework Do you ?
Django REST framework Is a powerful and flexible Web API Tools . Use RESTframework What are the reasons for this :
Web browsable API It is of great benefit to developers Include OAuth1a and OAuth2 The authentication strategy of Support ORM He Fei ORM Serialization of data resources
Full custom development – If you don't want to use more powerful functions , You can only use conventional function-based views Additional documentation and strong community support
158. Yes cookies And session Understanding ? Can they use it alone ?
Session The solution is to keep state on the server side , and Cookie The solution is to keep the state on the client side . But it's forbidden Cookie You can't get Session. because Session Yes, it is Session ID To determine the server for the current session Session, and Session ID It's through Cookie To deliver , Ban Cookie amount to SessionID, You don't get Session.
Reptiles
159. Try to list at least three popular large databases 160. List the... You have used Python Network packets used by web crawlers ?
requests, urllib,urllib2, httplib2
161. Which database is used to store data after crawling data , Why? ? 162. What crawler frameworks or modules have you used ? Advantages and disadvantages ?
Python Bring their own :urllib,urllib2 The third party :requests frame : Scrapy
urllib and urllib2 Modules all do and request URL Related operations , But they offer different functions . urllib2: urllib2.urlopen You can accept a Request Object or url,( In an interview with Request Object time , And you can set up a URL Of headers),urllib.urlopen Receive only one url. urllib Yes urlencode,urllib2 No, , So always urllib, urllib2 The reason why they are often used together scrapy It's a packaged framework , He includes a downloader , Parser , Log and exception handling , Based on Multithreading ,twisted How to deal with , For fixed single site crawling development , There are advantages , But for multi site crawling 100 Website , Concurrent and distributed processing is not flexible enough , Inconvenient to adjust and expand requests It's a HTTP library , It's just for asking , It is a powerful library , download , Parse all by yourself , High flexibility
Scrapy advantage : asynchronous ,xpath, Powerful statistics and log System , Support for different url.shell Easy to debug independently . Write middleware Easy to filter . It is stored in the database through pipeline 163. Writing a crawler is good with multiple processes ? It's better to multithread ? 164. Common anti crawlers and Countermeasures ?
165. What are the most commonly used parsers for parsing web pages ? 166. Web pages that need to be logged in , How to solve the limitation at the same time ip,cookie,session 167. Verification code solution ?
168. Use the most databases , Their understanding ? 169. What crawler middleware have you written ? 170.“ Polar test ” How to crack the sliding verification code ?
171. How often do reptiles climb , How to store the data when you climb down ? 172.cookie Overdue processing problems ?
173. How to deal with dynamic loading with high timeliness requirements ? 174.HTTPS What are the advantages and disadvantages ?
175.HTTPS How to realize the safe transmission of data ? 176.TTL,MSL,RTT What are they ?
177. Talk about you Selenium and PhantomJS understand
178. How to use agents ?
179. Stored in the database (redis、mysql etc. ). 180. How to monitor the status of reptiles ?
181. Describe below scrapy The mechanism by which the framework works ? 182. Talk to you about Scrapy The understanding of the ?
183. How to make scrapy The framework sends a post request ( Write it out )
184. How to monitor the status of reptiles ? 185. How to judge whether the website is updated ?
186. picture 、 Video crawling how to bypass the anti-theft connection
187. How much data do you climb out ? How often do you climb ?
188. What database is used to store the data climbed down ? Did you do the deployment ? How to deploy ? 189. Incremental crawling
190. How to remove the weight of the data climbed down , The way scrapy The specific algorithm basis .
191.Scrapy Advantages and disadvantages ?
192. How to set the crawl depth ?
193.scrapy and scrapy-redis What's the difference? ? Why choose redis database ?
194. What problems do distributed crawlers mainly solve ?
195. What is distributed storage ?
196. What do you know about distributed crawler schemes ?
197.scrapy-redis, Have you ever done any other distributed crawlers ?
 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved