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

Summary of 125 Python interview questions

編輯:Python

Pyhton Interview treasure

The most effective way to improve your programming ability is to knock the code

Author's brief introduction : Hello, I am programming ID
Personal home page : Programming ID Of csdn Blog
Series column :Python
Recommend a programming question brush artifact Click jump to enter the website

1. One line of code 1-100 The sum of the

res=sum(range(1,101))
print(res) #5050

2. How to modify global variables inside a function

a=5
def func():
global a
a=10
return a
func()
print(a) #10

3. List 5 Common use Python Standard library ?

 Commonly used
os Provides functions associated with the operating system
import os
os.getcwd()
os.path.join('/usr/temp','test.log')
datatime Provides common methods for date and time processing
from datetime import datetime
# Convert timestamps to date types 
datetime.fromtimestamp(1638175727)
datetime.strptime('2021-12-01 13:13:13','%Y-%m-%d %H:%M:%S')
datetime.now()
random Random number generation library
import random
# Generate 1-100 The random number 
print(random.randint(1,100))
# stay abcdef Choose one randomly 
print(random.choice('abcdef'))
math Math library
import math
print(math.pow(2,4))
print(math.sin(1))
print(math.floor(2.5))
re Regular matching module
import re
# Compile regular expressions into Pattern object 
pattern = re.compile(r'hello')
# Use Pattern Matching text , Get a match , Will return... If it cannot be matched None
match = pattern.match('hello world!')
if match:
# Use Match Get group information 
print(match.group())
# Search the entire string 
m = re.search('[a-z]+','abcdef123ghh')
print(m.group(0))
m2 = re.search('[0-9]+','abcdef123ghh')
print(m2.group(0))

4. How to merge two dictionaries

#4、 How to merge two dictionaries 
dic1={
'name':'psy'}
dic2={
'age':18}
dic1.update(dic2)
print(dic1) #{'age': 18, 'name': 'psy'}

5. Talk about it. Python Of GIL

#5、 Talk about it. Python Of GIL
"""

GIL yes Python The global interpreter lock , If there are multiple threads in the same process , A thread is running Python The program will take up Python Interpreter ( Add a lock GIL), send
Other threads in this process cannot run , Other counties can only run after the thread runs . If the thread encounters a good operation during running , Explain that the lock is unlocked , Make other threads run .
So in multithreading , Threads still run in sequence , Not at the same time .

Add : Multi process, because each process can be allocated resources by the system , This is equivalent to one for each process Python Interpreter , So multiple processes can run at the same time ,
The disadvantage is that the overhead of system resources is large .
“”"
6、Python Achieve list de duplication 【 And ensure the original order 】

#6、Python Achieve list de duplication 【 And ensure the original order 】
num_list = [1, 3, 1, 5, 3, 6, 1]
new_num=[]
jh=set()
for item in num_list:
if item not in jh:
new_num.append(item)
jh.add(item)
print(new_num) #[1, 3, 5, 6]
res=[num for num in set(num_list)] # Method 2
print(res) #[1, 3, 5, 6]

7、fun(args,kwargs) Medium args, kwargs What do you mean ?

#7、fun(args,kwargs) Medium args, kwargs What do you mean ?
"""
*arg Indicates that the data passed in is a non key value pair , The primitive type
**kwargs It means that the key value pair data is passed in , Dictionary type

If you have other language foundation , You should have heard of the concept of overloading , Yes Python In order to avoid this kind of tedious situation , Introduced args and kwargs;
args Used to accept data that is not a key value pair , Tuple type , and kwargs Is used to accept key value pair data , Dictionary type .
“”"
8. Python2 and Python3 Of range(100) The difference between ?

#8、Python2 and Python3 Of range(100) The difference between ?
python2 Back to the list
python3 The return is an iterator , Saving resource

9. Generate a 16 Bit random string

#9、 Generate a 16 Bit random string 
import random
import string # string.printable Randomly generate strings , The length is 100
res=''
for i in range(16):
res=res+random.choice(string.printable)
print(res) #G)_$U/#[email protected];6#
print(''.join((random.choice(string.printable)) for i in range(16))) #[email protected]}Z+Z(CS~5 AZ!+ 【 Method 2】

10、 In a word, explain what kind of language can be used with decorators ?

#10、 In a word, explain what kind of language can be used with decorators ?

Functions can be passed as arguments
11、python Built in data types

#11、python Built in data types 
# integer int Boolean type bool character string str list list Yuan Zu tuple Dictionaries dict

12、 In this paper, a brief introduction of object-oriented is given new and init difference ?

#12、 In this paper, a brief introduction of object-oriented is given new and init difference ?
(1)__new__ At least one parameter is required cls, Represents the current class , This parameter is instantiated by python The interpreter automatically recognizes
(2)__new__ There must be a return value , Return the instantiated instance , This is achieved by myself __new__ We should pay special attention to it !
Sure return Parent class ( adopt super( The name of the class ,cls)).__new__ The examples come out , Or directly object Of __new__ The examples come out .
(3)__new__ There is a parameter self, This is this. __new__ The returned instance ,__init__ stay __new__ On the basis of this, we can complete 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__ function , adopt return Statement __new__ The first argument to the function is cls To ensure that it is the current class instance ,
If it's the class name of another class , Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__ function , No other classes will be called __init__ function
"""#【 Here's an example 】 #__init__ and __new__ The difference between class Person(object): def __new__(cls,name,age): print('__new__ called') return super(Person,cls).__new__(cls) def __init__(self,name,age): print('__init__ called') self.name=name self.age=age def __str__(self): return 'Person:{}-{}'.format(self.name,self.age) child=Person('psy',18) print(child) """ Results show :
__new__ called
__init__ called
Person:psy-18

indicate :

__new__ Is better than __init__ Method ;
__new__ Method is responsible for creating an instance object ,__init__ Method is responsible for initializing the instance object ;
__new__ Method to formally create the method of this class instance , The object of the return amount is formal __init__ Of self Parameters ;
__init__ Used to instantiate objects ,__new__ Used to inherit , Is a category level method
#__new__ Application scenarios of 
#__new__ The main way is when you inherit something immutable class when ( such as int, str, tuple), Give you a way to customize the instantiation process of these classes 
class PositiveInt(int):
def __new__(cls,value):
return super(PositiveInt,cls).__new__(cls,abs(value))
print(PositiveInt(-55)) #55
class RoundFloat(float):
def __new__(cls,value):
return super(RoundFloat,cls).__new__(cls,round(value,2))
print(RoundFloat(3.1415926))

13、 sketch with Method to open the processing file to help me what we did ?

""" When opening a file for reading and writing , There may be some abnormal conditions , If you follow the routine f.open How to write it , We need to try,except,finally, Make abnormal judgment , And in the end, whatever happens to the file , To perform all finally f.close() Close file . Which uses with Methods help us achieve finally Medium f.close(). """

14、 list [1,2,3,4,5], Please use map() Output function [1,4,9,16,25], And use list derivation to extract greater than 10 Number of numbers , Final output [16,25]?

#14、 list [1,2,3,4,5], Please use map() Output function [1,4,9,16,25], And use list derivation to extract greater than 10 Number of numbers , Final output [16,25]?
l1=[1,2,3,4,5]
print(list(map(lambda x:x*x,l1))) #[1, 4, 9, 16, 25]
print([x for x in list(map(lambda x:x*x,l1)) if x>10]) #[16, 25]

15、python To generate random integers 、 Random decimal 、2-6 Between decimal method ?

#15、python To generate random integers 、 Random decimal 、2-6 Between decimal method ?
print(random.randint(1,10)) # Random integers 
print(random.random()) # Random decimal 
print(random.uniform(2,6)) #2-6 Decimal between 

16、 Avoid escaping which letter to add to the string to represent the original string ?

#16、 Avoid escaping which letter to add to the string to represent the original string ?
res=b'input\n' #bytes Byte character , Print to b start 
print(res) #b'input\n'
res=r'input\n' # Non escape native characters , Processed '\n' Turned into '\' and 'n'. That is to say \n It means two characters , Not a new line .
print(res) #input\n
res=u'input\n' # unicode Encoded characters ,python3 Default string encoding .
print(res) #input + Line break 

17、 < di v class=“nam”> Python, Use regular matching to find the content in the tag (“Python”), among class The class name of is uncertain .

#17、<div class="nam">Python</div>, Use regular matching to find the content in the tag (“Python”), among class The class name of is uncertain .
import re
s='<div class="nam">Python</div>'
res=re.findall(r'<div class=".*">(.*?)<.*>',s)[0]
print(res) #Python

18、Python Examples of interruptions ?

#18、Python Examples of interruptions ?
age = 10
#assert 0 < age < 10
""" Results show : Traceback (most recent call last): File "E:/000 Code of the article /27/python Interview questions .py", line 157, in <module> assert 0 < age < 10 AssertionError """

19、dict in fromkeys Usage of

#19、dict in fromkeys Usage of 
keys=('info1','info2')
res=dict.fromkeys(keys,['psy',18,'girl'])
print(res) #{'info1': ['psy', 18, 'girl'], 'info2': ['psy', 18, 'girl']}

20、 Please use regular expression to output Chinese characters

import re
s="not 404 found China 2018 I love you! "
r1='[a-zA-Z0-9’!"#$%&\'()*+,-./:;<=>[email protected],.?*、…【】《》?“”‘’![\\]^_`{|}~]+\s?'
res=re.sub(r1,'',s)
print(res) # China I love you! 

21、Python2 and Python3 difference ? list 5 individual

#21、Python2 and Python3 difference ? list 5 individual 
""" (1) Remove <>, All use != (2)print All need to be added () (3)xrange() Change it to range() (4) Memory operations cStringIO Change it to StringIO (5) Join in nonlocal effect : External non global variables can be referenced (6)zip() map() and filter() All return iterators , Not a generator , More memory saving """

22、 List Python Variable data type and immutable data type in , Why? ?

""" Immutable type :int str tuple Variable type :list dict set principle : Variable data types share a common memory address , Immutable data type means that each field of an object will generate a memory address """

23、dict Internal implementation ?

""" stay Python in , The dictionary is implemented through a hash table . in other words , A dictionary is an array , The index of the array is obtained after the key is processed by the hash function . The purpose of the hash function is to distribute the keys evenly in the array . Because different keys may have the same hash value , That is, there may be conflict , Advanced hash functions can minimize the number of conflicts . """

24、s = “ajldjlajfdljfddd”, De duplication and sort output from small to large "adfjl"?

s='ajldjlajfdljfddd'
res1=sorted(list(set(s))) #['a', 'd', 'f', 'j', 'l']
res=''.join(res1)
print(res) #adfjl

25、 use lambda Function to multiply two numbers ?

mul=lambda x,y:x*y
print(mul(2,5)) #10

26、 Dictionaries are sorted by key from small to large ?

info = {
'name': 'Gage', 'location':'nj', 'sex': 'man'}
res_key=sorted(info.items(),key=lambda x:x[0]) # Sort by key 
print(res_key) #[('location', 'nj'), ('name', 'Gage'), ('sex', 'man')]
res_value=sorted(info.items(),key=lambda x:x[1]) # Sort by value 
print(res_value) #[('name', 'Gage'), ('sex', 'man'), ('location', 'nj')]
# If you sort the dictionaries in the list 
l=[{
'name':'psy','age':18},{
'name':'xk','age':24},{
'name':'pyg','age':55}]
# Sort by age 
l.sort(key=lambda item:item['age'])
print(l) #[{'name': 'psy', 'age': 18}, {'name': 'xk', 'age': 24}, {'name': 'pyg', 'age': 55}]
salaries={
'psy':200,'xk':180,'gyp':300,'pyg':250}
# take salaries Sort by salary 
res=sorted(salaries,key=lambda item:salaries[item],reverse=True)
print(res) #['gyp', 'pyg', 'psy', 'xk']

27、Python Get current date ?

import time
import datetime
print(datetime.datetime.now()) #2019-04-03 17:06:16.347417
print(time.strftime('%Y-%m-%d %H:%M:%S')) #2019-04-03 17:06:51

28、 sketch 5 strip :Python Of pep8- Code specification

Don't put a semicolon at the end of the line , And don't use semicolons to put two commands on the same line
Don't use backslashes to connect lines
Do not use parentheses in return statements or conditional statements
Empty space between top-level definitions 2 That's ok , Null between method definitions 1 That's ok , There are two empty lines between the top-level definitions
If a class does not inherit from other classes , It's obvious from object Inherit

29、Fibonacci The sequence

def func(n):
a,b=0,1
while n:
yield b
a,b=b,a+b
n-=1
print(list(func(10))) #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

30、Python Three mesh operation

#res=a-b if a>b else b-a
# explain : If a>b establish , return a-b, Otherwise return to b-a

31、 The singleton pattern 【 The following articles will focus on the singleton mode 】

class Single():
__isstance=None
__first_init=False
def __new__(cls, *args, **kwargs):
if not cls.__isstance:
cls.__isstance=object.__new__(cls)
def __init__(self,name):
if not self.__first_init:
self.name=name
Single.__first_init=True

32、 recursive

def digui(n):
if n==1:
return 1
else:
return (n*digui(n-1))
print(digui(4)) #24

33、 Count the number of occurrences of each word in the string

from collections import Counter
s3='kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h'
print(Counter(s3)) #Counter({'l': 9, ';': 6, 'h': 6, 'f': 5, 'a': 4, 'j': 3, 'd': 3, 's': 2, 'k': 1, 'b': 1, 'g': 1})

34、 Regular re.complie effect

#re.complie Is to program a regular expression into an object , Speed up , And it can be reused 
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex=re.compile('\w*o\w*')
res=regex.findall(content)
print(res) #['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']

35、filter Method to find all the odd numbers in the list and construct a new list ,a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a=[1,2,3,4,5,6,7,8,9,10]
res=list(filter(lambda x:x%2,a))
print(res) #[1, 3, 5, 7, 9]

36、 The list derivation finds all odd numbers in the list and constructs a new list ,a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a=[1,2,3,4,5,6,7,8,9,10]
res=[x for x in a if x%2==1]
print(res) #[1, 3, 5, 7, 9]

37、a=(1,)b=(1),c=(“1”) What types of data are they ?

a=(1,)
print(type(a)) #<class 'tuple'>
b=(1)
print(type(b)) #<class 'int'>
c=("1")
print(type(c)) #<class 'str'>

37、 Two lists [1,5,7,9] and [2,2,6,8] Merge into [1,2,2,3,6,7,8,9] 【 Merge sort 】
l1=[1,5,7,9]
l2=[2,2,6,8]

def merge_sort(l1,l2):
left_p,right_p=0,0
result=[]
while left_p<len(l1) and right_p<len(l2):
if l1[left_p]<l2[right_p]:
result.append(l1[left_p])
left_p+=1
else:
result.append(l2[right_p])
right_p+=1
result+=l1[left_p:]
result+=l2[right_p:]
return result
print(merge_sort(l1,l2))

38、 use python Delete files and use linux Command delete file method

""" python Delete file : os.remove( file name ) linux Command to delete files : rm file name """

39、logging Use of modules ?

#logging It is a log module , Reptiles may use 
import logging
logging.basicConfig(level=logging.INFO,format='%(asctime)s-%(name)s-%(levelname)s-%(message)s')
logger=logging.getLogger('psy') #psy The file name I set 
logger.info('Start log')
logger.debug('Do something')
logger.warning('Something maybe fail')
logger.error('Somthing exists error')
logger.critical('Break down')

40、 Write a custom exception code

def func():
try:
for i in range(5):
if i>2:
raise Exception(' Number is greater than 2')
except Exception as e:
print(e)
func() # Number is greater than 2

41、 Regular expression matching ,(.) and (.?) Match the difference ?

#(.*) It's a greedy match , We'll match as many back matches as possible that satisfy the regularity 
#(.*?) Greedy match between right and wrong , Will match as few as possible that satisfy the regularity 
s = "<a> ha-ha </a><a> ha-ha </a>"
import re
res1 = re.findall("<a>(.*)</a>", s)
print(" Greedy matching ", res1) # Greedy matching [' ha-ha </a><a> ha-ha ']
res2 = re.findall("<a>(.*?)</a>", s)
print(" Non greedy matching ", res2) # Non greedy matching [' ha-ha ', ' ha-ha ']

42、[[1,2],[3,4],[5,6]] One line of code expands the list , obtain [1,2,3,4,5,6]

a=[[1,2],[3,4],[5,6]]
new_a=[]
for item in a:
new_a.extend(item)
print(new_a) #[1, 2, 3, 4, 5, 6]
res=[j for i in a for j in i]
print(res) #[1, 2, 3, 4, 5, 6]

43、x=“abc”,y=“def”,z=[“d”,“e”,“f”], Find out separately x.join(y) and x.join(z) The result returned

#join() In parentheses are iteratable objects ,x Insert in the middle of an iteratable object , Form a string , Consistent result 
x="abc"
y="def"
z=["d","e","f"]
print(x.join(y)) #dabceabcf
print(x.join(z)) #dabceabcf

44、 For example, in the exception module try except else finally The relevance of

""" try..except..else No exception was caught , perform else sentence try..except..finally Whether or not an exception is caught , All implemented finally sentence """
#45、python Exchange two values in 
a,b=1,2
a,b=b,a
print(a,b) #2 1

46、 Illustrate with examples zip() The usage function zip() The essence of function is integration

l1=[1,2,3,4]
l2=[4,5,6]
res=list(zip(l1,l2))
print(res) #[(1, 4), (2, 5), (3, 6)]

47、a=“ Zhang Ming 98 branch ”, use re.sub, take 98 Replace with 100

import re
a=" Zhang Ming 98 branch "
res=re.sub(r'\d+','100',a)
print(res) # Zhang Ming 100 branch 

48、a="hello" and b=" Hello " Code as bytes type

a=b"hello"
b=" Hello ".encode()
print(type(a)) #<class 'bytes'>
print(type(b)) #<class 'bytes'>

49、[1,2,3]+[4,5,6] What's the result of

print([1,2,3]+[4,5,6]) #[1, 2, 3, 4, 5, 6]

50、 Improve python The way to run efficiency

(1) Using the generator , Because it can save a lot of memory
(2) Loop code optimization , Avoid too much repetitive code execution
(3) For core modules Cython PyPy etc. , Increase of efficiency
(4) Multithreading 、 Multi process 、 coroutines
(5) Multiple if elif conditional , You can put the most likely conditions in front of you and write , This can reduce the number of judgments of the program , Increase of efficiency

51、 encounter bug How to deal with it

(1) Mistakes in detail , adopt print() Print , Can be carried out to print() Generally speaking, there is no problem with the above code , Is there a problem with the segmented detection program , If it is js If you like, you can alter live console.log
(2) If some third-party frameworks are involved , I will go to find the optical documents or some technical blogs
(3) about bug Management and classification summary of , The general test will test out bug use teambin etc. bug Management tools to record , Then we'll make changes one by one , The process of modification is also a way to understand business logic and improve the rigor of your own programming logic , Then make some notes by yourself .
(4) The problem of leading package 、 The display error caused by polyphonic characters in urban positioning

52、list=[2,3,5,4,9,6], Sort from small to large , Don't use sort, Output [2,3,4,5,6,9]

# If you use sort
l=[2,3,5,4,9,6]
print(sorted(l)) #[2, 3, 4, 5, 6, 9]
# Don't use sorted, Define your own functions 
def quicksort(old_list):
if len(old_list)<2:
return old_list
else:
temp=old_list[0]
lowbeforetemp=[i for i in old_list[1:] if i<=temp]
bigbeforetemp=[i for i in old_list[1:] if i>temp]
final_list=quicksort(lowbeforetemp)+[temp]+quicksort(bigbeforetemp)
return final_list
print(quicksort([2,3,5,4,9,6])) #[2, 3, 4, 5, 6, 9]

53、 Divide two numbers , Keep two decimal places

print(round(10/3,2)) #3.33

54、 Regular matching , Match date 2018-03-20

s='Date:2018/03/20'
import re
res1=re.findall('(\d+)',s) #['2018', '03', '20']
res='-'.join(res1)
print(res) #2018-03-20

55、 Use pop and del Delete the "name" and "age" Field ,dic={“name”:“zs”,“age”:18,“sex”:“girl”}

dic={
"name":"zs","age":18,"sex":"girl"}
dic.pop("name")
print(dic) #{'sex': 'girl', 'age': 18}
del dic["age"]
print(dic) #{'sex': 'girl'}

56、 A brief introduction to multithreading 、 Multi process
Process is resource (CPU、 Memory, etc. ) Assigned base unit , It is an instance of the execution of a program .
Thread is the smallest unit of program execution , It is an execution flow of a process .
Process has its own independent address space , Every time a process is started , The system will allocate address space for it , Create data tables to maintain code snippets 、 Stack and data segments , This kind of operation is very expensive .
【 So each process has its own address space , Don't disturb each other 】
Threads share data in a process , Use the same address space , therefore CPU Switching a thread costs much less than a process , At the same time, the cost of creating a thread is much smaller than that of a process .

57、 sketch any() and all() Method
# Even a return is bool value all If there is 0 None False return False, Otherwise return to

True;any By contrast
print(all([0,1,2,3])) #False
print(all([1,2,3])) #True
print(any([0,1,2,3])) #True
print(any([0,False,None])) #False

58、 Anomaly classification

""" IOError I / O is abnormal AttributeError Trying to access a property that an object does not have ImportError Cannot import module or package , It's basically a path problem IndentationError Grammar mistakes , The code is not properly aligned KeyError Trying to access a key that doesn't exist in your dictionary SyntaxError Python Code logic syntax error , Cannot perform NameError Use a variable that has not been assigned to an object """

59、Python in copy and deepcopy difference 【 Deep copy and light copy 】

import copy
#copy Use 
l1=[1,2,[3,4]]
l2=copy.copy(l1)
print(id(l1)==id(l2)) #False both id inequality 
l1.append(5)
l1[2].append(5)
print(l1) #[1, 2, [3, 4, 5], 5]
print(l2) #[1, 2, [3, 4, 5]]
#deepcopy Use 
l1=[1,2,[3,4]]
l2=copy.deepcopy(l1)
print(id(l1)==id(l2)) #False both id inequality 
l1.append(5)
l1[2].append(5)
print(l1) #[1, 2, [3, 4, 5], 5]
print(l2) #[1, 2, [3, 4]]
""" copy() and deepcopy() yes Python Language copy Two of the modules method,copy() It's actually with deep copy Relative shallow copy. For simple object, use shallow copy and deep copy No difference . complex Object, Such as list Middle sleeve list The situation of ,shallow copy The son of list Not from the original object Really independent , So if you change the original object The son of list An element in , Yours copy Will change with it . deep copy Is more in line with our intuitive definition of replication : Once it's copied , It should be independent . """

60、 stay python Replication methods in data processing ( Let's introduce 3 Kind of , Import required numpy library )

import numpy as np

Method 1 :b=a 【 here :b and a Actually point to the same thing , change a or b, The two change together 】

a=np.arange(12)
b=a
b.shape=(3,4)
print(a.shape) #(3, 4)
print(id(a)==id(b)) #True

Method 2 :c=a.view() 【 here :c and a Not pointing to the same thing , But share a stack of values 】
a=np.arange(12)

c=a.view()
c.shape=(3,4)
print(a.shape) #(12,)
print(id(a)==id(c)) #False

Method 3 :d=a.copy() 【 here :d and a Each is its own value , It doesn't matter 】

a=np.arange(12)
d=a.copy()
d[0]=5
print(a) #[ 0 1 2 3 4 5 6 7 8 9 10 11]
print(d) #[ 5 1 2 3 4 5 6 7 8 9 10 11]
print(id(a)==id(d)) #False

61、 List several magic methods and briefly introduce their uses

""" __init__ Object initialization method __new__ The method executed when the object is created , The singleton mode uses __str__ Then used print When exporting objects , As long as you define __str__(self) Method , Then it will be printed in this method return The data of 【 There must be return】 __del__ Methods to delete object execution """

62、 Context manager with…as The implementation of the

Context manager (context manager) Used to specify the scope of use of an object . Once you enter or leave the scope of use , Special operations will be called Such as allocating or freeing memory for objects ).
Its grammatical form is with…as…
Common context managers : with open(‘test.txt’,‘w’)as f:f.write(‘Hello World!’)
open Function can be used as a simple function , It can also be used as a context manager . This is because open Function returns a file type variable .

To implement the context manager , Two methods must be implemented : A preparation operation that is responsible for entering a statement block (enter Method ), The other is responsible for the aftermath of leaving the statement block (exit Method ).
When an object is used as a context manager :
enter Method will be called before entering the code block .
exit Method is called after leaving the code block ( Even if an exception is encountered in the code block ).

Self implemented context management method ,

class PypixOpen:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.openedFile = open(self.filename, self.mode)
return self.openedFile
def __exit__(self, *unused):
self.openedFile.close()
with PypixOpen(filename, mode) as writer:
writer.write("Hello World from our new Context Manager!")

Be careful :
(1) We completely ignore the possible problems inside the statement block .
(2) If an exception occurs inside the statement block ,__exit__ Method will be called , The exception will be thrown again (re-raised).
When processing file write operations , Most of the time you certainly don't want to hide these exceptions , So it's ok .
For exceptions that you don't want to throw again , We can get __exit__ Method simply returns True To ignore all exceptions that occur in the statement block ( In most cases, this is not a wise move ).
(3) Above code *unused Point to exc_type, exc_value, traceback Three parameters , When an exception occurs in the program block (exception), These three parameters are used to describe the exception .
We can perform corresponding processing according to these three parameters . If normal operation ends , These three parameters are None.

The answer given

class Close():
def __init__(self,obj):
self.obj=obj
def __enter__(self):
return self.obj # Return as as The goal is 
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self.obj.close()
except AttributeError:
print(exc_type)

63、python arg.py 1 2 The command line starts the program and passes parameters ,print(sys.argv) What data will be output ?

#[arg.py 1 2]

64、 Please put [i for i in range(3)] Change to generator

class iter():
def __init__(self,data):
self.data=data
self.loop=-1
def __iter__(self):
return self
def __next__(self):
if self.loop>=self.data:
raise StopIteration
self.loop+=1
return self.loop
Iter=iter(range(3))
print(Iter) #<__main__.iter object at 0x000001BA9D92F898>
print(Iter.__iter__()) #<__main__.iter object at 0x0000016888BDF898>
print(Iter.data) #range(0, 3)
print(Iter.__next__) #<bound method iter.__next__ of <__main__.iter object at 0x0000016888BDF898>>
""" # List resolution generate list [x*x for x in range(3)] result :[0,1,4] # Generator Expressions (x*x for x in range(3)) result :(0,1,4) # The conversion between the two list(x*x for x in range(3)) result [0,1,4] """

65、 String conversion case ?

s='MyDay'
print(s.upper()) #MYDAY
print(s.lower()) #myday

66、 Please explain sort and sorted The difference between sorting a list

l=[2,4,1,3,8,6,5]
l.sort()
print(l) #[1, 2, 3, 4, 5, 6, 8]
l=[2,4,1,3,8,6,5]
print(sorted(l)) #[1, 2, 3, 4, 5, 6, 8]
"""

(1)sort() And sorted() The difference is :sort() It's rearranging the list in place , and sorted() It's generating a new list
sorted(L) Returns a sorted L, Don't change the original L;L.sort() It's about the original L To operate , After calling the original L Will change , no return value
therefore a=a.sort() It's wrong. ,a=sorted(a) That's right !
(2)sorted() Applicable to any iteratable container ,list.sort() Support only list
(3) Based on the above two points ,sorted Frequency ratio of list.sort() Higher

67、 Yes foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4] Sort , Use lambda Functions sort from small to large

# Method 1 : Use it directly list.sort()
foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
foo.sort()
print(foo) #[-20, -5, -4, -4, -2, 0, 2, 4, 8, 8, 9]
# Method 2 : Use lambda function 
foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
res=sorted(foo,key=lambda x:x)
print(res) #[-20, -5, -4, -4, -2, 0, 2, 4, 8, 8, 9]
68、 Yes foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4] Sort , Increase the positive number from small to large , Negative numbers go from big to small
foo = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
res=sorted(foo,key=lambda x:(x<0,abs(x)))
print(res) #[0, 2, 4, 8, 8, 9, -2, -4, -4, -5, -20]
#69、Python Is the parameter transferred by value or address ?
""" Python Function parameter in is reference passing ( Note that it's not worth passing on ). For immutable types ( Numerical type 、 character string 、 Tuples ), Dependent variables cannot be modified , So the operation doesn't affect the variable itself ; For variable types ( List dictionary ) Come on , A function body operation may change an incoming parameter variable . """

70、w、w+、r、r+、rb、rb+ File open mode difference

r Open the file read-only . The pointer to the file will be placed at the beginning of the file . This is the default mode .
w Open a file only for writing . Overwrite the file if it already exists , If the file does not exist , Create a new file .
a Open a file for appending . If the file exists , The file pointer will be placed at the end of the file . in other words : The new content will be written after the existing content .
If the file does not exist , Create a new file to write to .
rb Open a file in binary format for read-only use . The file pointer is placed at the beginning of the file . This is the default mode .
wb Opening a file in binary format is only used for writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .
ab Open a file in binary format for appending . If the file already exists , The file pointer will be placed at the end of the file . That is to say : The new content will be written after the existing content .
If the file does not exist , Create a new file to write to .
r+ Open a file for reading and writing . The file pointer will be placed at the beginning of the file .
w+ Open a file for reading and writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .
a+ Open a file for reading and writing . If the file already exists , The file pointer will be placed at the end of the file . The mode is appended when the file is opened .
If the file does not exist , Create a new file to write to .
rb+ Open a file in binary format for reading and writing . The file pointer is placed at the beginning of the file .
wb+ Open a file in binary format for reading and writing . Overwrite the file if it already exists . If the file does not exist , Create a new file .
ab+ Open a file in binary format for reading and writing . If the file already exists , The file pointer will be placed at the end of the file .
If the file does not exist , Create a new file to write to .

71、int(“1.4”)、int(1.4) Output result of ?

print(int("1.4")) # Report errors ValueError: invalid literal for int() with base 10: '1.4'
print(int(1.4)) #1

72、Python Garbage collection mechanism ?
“”"
(1) Reference count

import sys
str1='hello world'
print(sys.getrefcount(str1)) # stay python Run under the interpreter , by 2 To create a , Call once 

(2) Generational counting
Python Three generations of object sets are defined by default , The greater the number of indexes , The longer the object lives
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 .】
(3) Reference loop
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 o1.x == o2 and o2.x == 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.
“”"
73、Python Dictionary and json String conversion method 【 Serialization and deserialization 】

import json
dic={
"name":"psy","age":18}
# serialize hold python The object code of is converted to json Format string 
res1=json.dumps(dic)
print(res1,type(res1)) #{"age": 18, "name": "psy"} <class 'str'> 【json Generally used in ""】
# Deserialization hold json Format string decoded to python Data objects .
res2=json.loads(res1)
print(res2,type(res2)) #{'name': 'psy', 'age': 18} <class 'dict'>

74、Python Regular search and match The difference between

""" match() Start with the first character , If the first character does not match, it returns None, Don't continue to match . Used to determine whether the beginning of a string or the entire string matches , Fast . search() Will find the entire string , Until we find a match . """
import re
str1='superman'
str2='hello superman'
print(re.match('super',str1)) #<_sre.SRE_Match object; span=(0, 5), match='super'>
print(re.match('super',str1).span()) #(0, 5)
print(re.match('super',str2)) #None
print(re.search('super',str1)) #<_sre.SRE_Match object; span=(0, 5), match='super'>
print(re.search('super',str1).span()) #(0, 5)
print(re.search('super',str2)) #<_sre.SRE_Match object; span=(6, 11), match='super'>
print(re.search('super',str2).span()) #(6, 11)

75、Python Read from Csv、Excel Method of file ?

import pandas as pd
#read_csv=pd.read_csv('test1.csv')
#read_excel=pd.read_excel('test2.xlsx')

76、 Enter the date , Judge the day as the day of the year ?

import datetime
def DayOfYear():
year=input(' Please enter the year :').strip()
mon=input(' Please enter the month :').strip()
day=input(' Please enter the day :').strip()
data1=datetime.date(year=int(year),month=int(mon),day=int(day))
data2=datetime.date(year=int(year),month=1,day=1)
return (data1-data2).days+1
print(DayOfYear())
""" Running results : Please enter the year :2019 Please enter the month :4 Please enter the day :18 108 """

77、 What is? lambda function ? What are the benefits ?

lambda Function is a function that can take any number of parameters ( Including optional parameters ) And an anonymous function that returns a single expression value
benefits :
(1)lambda The function is light , Delete as you go , It's very suitable for a function that needs to be completed , But this function is only used here , Even the name is very casual ;
(2) Anonymous functions , Usually used to give filter,map Such a functional programming service ;
(3) As a callback function , To some applications , Like message processing

78、 Finding the intersection of two lists 、 Difference set 、 Combine
set() There is about intersection in the set 、 Difference set 、 The method of Union intersection intersection() Difference set difference Combine union

a=[1,2,3,4]
b=[4,3,5,6]
jj1=[i for i in a if i in b]
jj2=list(set(a).intersection(set(b)))
print(' intersection :',jj1,jj2) # intersection : [3, 4] [3, 4]
cj1=list(set(a).difference(set(b)))
cj2=list(set(b).difference(set(a)))
print(' Difference set :',cj1,cj2) # Difference set : [1, 2] [5, 6]
bj=list(set(a).union(set(b)))
print(' Combine ',bj) # Combine [1, 2, 3, 4, 5, 6]
**79、 What is a negative index ?**
# Different from positive index , Negative index is to search from the right 

80、 Regular matching is not based on 4 and 7 Cell phone number at the end ?

import re
tels=["13100001234","18912344321","10086","18800007777"]
# Method 1:
for item in tels:
if len(item)!=11 or item.endswith('4') or item.endswith('7'):
print('{} Not the phone number you want '.format(item))
else:
print('{} Is the desired mobile number '.format(item))
# Method 2 :
for item in tels:
res=re.match("1\d{9}[0-3,5-6,8-9]",item)
if res:
print('{} Is the desired mobile number '.format(res.group()))
else:
print('{} Not the phone number you want '.format(item))

81、 There are two ways to remove spaces ?

str="hello world ha ha"
res1=str.replace(' ','')
print(res1) #helloworldhaha
res2_l=str.split(' ')
res2=''.join(res2_l)
print(res2) #helloworldhaha

82、 Count the number of times a character appears in a string ?

str=" Zhang San ha-ha Zhang San ha-ha Zhang San "
from collections import Counter
l=str.split(' ')
res=Counter(l)
print(res) #Counter({' Zhang San ': 3, ' ha-ha ': 1, ' ha-ha ': 1})
print(Counter(l)[' Zhang San ']) #3
print(str.count(' Zhang San ')) #3

83、 Regular Expression Matching URL

str = 'Its after 12 noon, do you know where your rooftops are?
import re
pattern=re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
url=re.findall(pattern,str)
print(url)

84、 Regular match to 163.com The mailbox at the end ?

email_list= ["[email protected]","[email protected]", "[email protected]" ]
import re
for item in email_list:
res=re.match('[\w]{4,20}@163\.com$',item)
if res:
print('{} Email address in compliance with regulations , The result of the match is :{}'.format(item,res.group()))
else:
print('{} Non compliant email address '.format(item))

85、s=“info:xiaoZhang 33 shandong”, Use regular segmentation string output [‘info’, ‘xiaoZhang’, ‘33’, ‘shandong’]

s="info:xiaoZhang 33 shandong"
import re
res=re.split(r":| ",s) #| Represents or , according to : or segmentation 
print(res) #['info', 'xiaoZhang', '33', 'shandong']

86、 Two have sequence tables ,l1,l2, Merging these two lists is not available extend 【 The previous question is very similar to …】

l1=[1,4,7]
l2=[2,5,6]
l1.extend(l2)
print(l1) #[1, 4, 7, 2, 5, 6] 【 disorder 】
l1=[1,4,7]
l2=[2,5,6]
def merge_sort(l1,l2):
left_p,right_p=0,0
result=[]
while left_p<len(l1) and right_p<len(l2):
if l1[left_p]<l2[right_p]:
result.append(l1[left_p])
left_p+=1
else:
result.append(l2[right_p])
right_p+=1
result+=l1[left_p:]
result+=l2[right_p:]
return result
print(merge_sort(l1,l2)) #[1, 2, 4, 5, 6, 7]

87、 Code description list derivation 、 Dictionary derivation 、 generator ?

import random
tds_list=[i for i in range(10)]
print(' List derivation ',tds_list,type(tds_list)) # List derivation [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
tds_dict={
k:random.randint(4,9) for k in ["a","b","c","d"]}
print(' Dictionary derivation ',tds_dict,type(tds_dict)) # Dictionary derivation {'d': 9, 'c': 6, 'a': 9, 'b': 7} <class 'dict'>
generate=(i for i in range(10))
print(' generator ',generate,type(generate)) # generator <generator object <genexpr> at 0x0000021C8A507410> <class 'generator'>

88、 Sort dictionaries by key , Not to be used zip?

dic = {
"name":"zs","sex":"man" ,"city":"bj"}
# Press the key on the dictionary key Sort 
res1=sorted(dic.items(),key=lambda x:x[0])
print(res1) #[('city', 'bj'), ('name', 'zs'), ('sex', 'man')]
# Values for Dictionary value Sort 
res2=sorted(dic.items(),key=lambda x:x[1])
print(res2) #[('city', 'bj'), ('sex', 'man'), ('name', 'zs')]

89、 Read the code and what their output is ?

def multi():
return [lambda x : i*x for i in range(4)]
print([m(2) for m in multi()]) #[6, 6, 6, 6]
""" ** analysis : This is a closure , Here is the definition of closure : 1、 A closure is a nested function 2、 Closures must return nested functions 3、 Nested functions must reference an external non global local free variable ** def multi(): func_list=[] for i in range(4): def lam(x): return i*x func_list.append(lam) return func_list stay python in , Relatively speaking, local variables are bound to values , Nonlocal variables are bound to space , Not the value itself . therefore ,for Loop generated i, Relative to the function lam Come on , Global variable , So the binding is i The memory address , but i And it turns into 3,lam The binding is 3. So it led to , The values of the four generated functions are the same . The result is [0,2,4,6] Well ? According to the idea just now , We just need to lam Function i Become local variable , The function lam Bound is the value , Instead of memory address : def mul(): func_list=[] for i in range(4): def lam(x,n=i): # This time because n It's a local variable , So the binding is n Value return x*n func_list.append(lam) return func_list print([m(2) for m in mul()]) #[0, 2, 4, 6] """

90、 Code implementation Python Thread synchronization of , Print in sequence on the screen 10 Time “ABC”

from threading import Thread,Lock
mutex=Lock()
def print1(lock):
lock.acquire()
print('A')
lock.release()
def print2(lock):
lock.acquire()
print('B')
lock.release()
def print3(lock):
lock.acquire()
print('C')
lock.release()
for i in range(10):
t1=Thread(target=print1,args=(mutex,))
t1.start()
t1.join()
t2 = Thread(target=print2, args=(mutex,))
t2.start()
t2.join()
t3 = Thread(target=print3, args=(mutex,))
t3.start()
t3.join()

91、 sketch read、readline、readlines The difference between ?

read Read entire file
readline Read next line , Using the generator method
readlines Read the entire file to an iterator for us to traverse

92、a=" hehheh " Remove the leading and trailing spaces

a=" hehheh "
print(a.strip()) #hehheh

93、yield Method

yield Is to save the current program execution state .
Do you use for In the cycle , Every time you take an element, it will be calculated . use yield The function of is called generator, and iterator equally .
The advantage is that you don't have to calculate all the elements at once , It's calculated once at a time , Can save a lot of space ,generator Each calculation requires the result of the last calculation , So use yield, Otherwise, once return, The last calculation result is gone .

94、 character string “123” convert to 123, Don't use built-in API, for example int()

def change(s):
num=0
for item in s:
n=eval(item) # here n by int type 
num=num*10+n
return num
res=change('123')
print(res,type(res)) #123 <class 'int'>

95、is and == The difference between

 **is Compare memory addresses == Compare content and data types **
a=[1,2,3]
b=a
print(id(a),id(b)) #1753026079880 1753026079880
print(a is b) #True
print(a == b) #True
import copy
c=copy.deepcopy(a)
print(id(a),id(c)) #1753026079880 1753026098120
print(a is c) #False
print(a==c) #True

96、 Is there a tool that can help you find python Of bug And static code analysis ?

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

97、 File recursion

import os
def print_directory_contents(s_path):
""" This function takes the name of the folder as an input parameter Returns the path of the file in the folder And the path to the files in the folder it contains """
for s_child in os.listdir(s_path):
s_child_path = os.path.join(s_path, s_child)
if os.path.isdir(s_child_path):
print_directory_contents(s_child_path)
else:
print(s_child_path)
print_directory_contents('D:\QQ') #D:\QQ\QQ_Setup.exe

98、Python how copy A file ?

#shutil The module has a copyfile Function can copy files copyfile(source_file, destination_file)**
from shutil import copyfile
copyfile('test.py','test_new.py') # Put... In this directory test.py Copy to... In the same directory test_new.py

99、 Disrupt a well ordered list object alist?

import random
alist = [1, 2, 3, 4, 5]
random.shuffle(alist)
print(alist) #[4, 1, 2, 3, 5]
**100、 Yes s="hello" Reverse **
s="hello"
print(s[::-1]) #olleh

101、Python Middle single underline and double underline use

foo: An agreement ,Python Internal name , Used to distinguish other user-defined names , In case of conflict , For example __init__(),del(),call() These special methods
_foo: An agreement , Used to specify variable private . A way for programmers to specify private variables . Out-of-service from module import * Import , Other aspects are accessed as public ;
__foo: This has a real meaning : The parser uses _classname__foo To replace the name , With the same name as other classes , It can't be accessed directly like a public member , By object name ._ Class name __xxx This way you can access .

102、 Invert an integer

class Solution(object):
def reverse(self, x):
if -10 < x < 10:
return x
str_x = str(x)
if str_x[0] != "-":
str_x = str_x[::-1]
x = int(str_x)
else:
str_x = str_x[1:][::-1]
x = int(str_x)
x = -x
return x if -2147483648 < x < 2147483647 else 0
s=Solution()
res=s.reverse(-120)
print(res) #-21

103、 Code describes static methods (staticmethod), Class method (classmethod) And instance methods

class Method():
def foo(self,x):
print('running foo {}-{}'.format(self,x))
@classmethod
def class_foo(cls,x):
print('running class_foo {}-{}'.format(cls,x))
@staticmethod
def static_foo(x):
print('running static_foo {}'.format(x))
m=Method()
m.foo('psy') #running foo <__main__.Method object at 0x000002498DF18B00>-psy
m.class_foo('psy') #running class_foo <class '__main__.Method'>-psy
m.static_foo('psy') #running static_foo psy

104、 The difference between the new type and the old type ?

a. stay python Rivan inherited object Class , It's all new
b. Python3 There are only new types in it
c. Python2 It's inherited object It's a new class , It's the classic class that doesn't write the parent class
d. Classic classes are currently in Python There's basically no application in it

105、 Please write a decorator and timer to output logs after the function is executed

""" Simple decorator templates : def outter(func): def wrapper(*args,**kwargs): f=func() return wrapper def timmer(func): # timer def wrapper(*args,**kwargs): start=time.time() func(*args,**kwargs) end=time.time() spend=round(end-start,2) print(' The execution time of this program is {}'.format(spend)) return wrapper """
def do_log(func): # Log decorator 
def wrapper(*args,**kwargs):
if func.__name__=='debug':
msg="debug {}".format(args[0])
elif func.__name__=='info':
msg="info {}".format(args[0])
else:
msg="{} {}".format(func.__name__,args[0])
return func(msg,**kwargs)
return wrapper
@do_log
def debug(msg):
print(msg)
@do_log
def info(msg):
print(msg)
debug('123') #debug 123
info('456') #info 456

106、 Please explain the advantages of cooperative process

Subroutine switching is not thread switching , It's controlled by the program itself
There is no overhead for thread switching , Ratio to multithreading , The more threads there are , The greater the performance advantage of the coroutine
No multi-threaded locking mechanism is required , Because there's only one thread , There is no conflict between writing variables at the same time , Control Shared resources without locking in the coroutine

107、 Closures must satisfy those points

1. Must have an embedded function
2. An embedded function must refer to a variable in an external function
3. The return value of an external function must be an embedded function

108、 Interview skills

What are your shortcomings ?
Shortcomings are really a very difficult question to answer , But as long as you master the following principles , This problem is just a piece of cake , That's it : evade the crucial point .
What is heavy ? Personality problems , Interpersonal problems , Work ability reasons . If you say :“ My weakness is my poor patience ”,“ My weakness is that my communication skills need to be improved ”, Then you are really a big fool .
What is light ? For example : I don't have a good sense of direction , Not good at managing money ( Except for financial positions ) And so on. . Someone will ask , I said these shortcomings , Will the interviewer think I am hypocritical ? I'll tell you , As long as your hypocrisy doesn't make him want to vomit ( such as “ My biggest weakness is that I'm too perfectionist ”), That hypocrisy is definitely better than stupid honesty .

Do you have anything to ask me ?
This question is usually asked , The whole interview is coming to an end , But don't take it lightly , Because the final question determines the interviewer's final impression of you .
So what is the subtext behind this question ? That's it : What else do you want to know , Help you stay in this company better ? In other words , Is how much you want to stay in this company ? If you say “ No, ”, Then the interviewer may have a heart thump : So that's all you're interested in …… This question actually gives you a chance to show your loyalty , You can ask her very seriously :“ If I come to this company , What will the daily routine be like ?” perhaps “ What is the atmosphere of the company ?”( Hint at your strong desire to work here ).

109、 De duplicate the list and keep the original order

# Method 1 
l1=[11,2,3,22,2,4,11,3]
res=[]
for item in l1:
if item not in res:
res.append(item)
print(res) #[11, 2, 3, 22, 4]
# Method 2 : utilize sort Method 
l1=[11,2,3,22,2,4,11,3]
l2=list(set(l1)) # Use the list as set duplicate removal , Convert back to list ( Not in the previous order )
l2.sort(key=l1.index) # Sort the list from the previous step , according to l1 Order in 
print(l2) #[11, 2, 3, 22, 4]

110、# Set the data in the list according to age Sort

l=[{
"name":"psy","age":18},{
"name":"mama","age":54},{
"name":"baba","age":55},{
"name":"xk","age":24},{
"name":"gyp","age":25}]
l.sort(key=lambda x:x["age"])
print(l) #[{'name': 'psy', 'age': 18}, {'name': 'xk', 'age': 24}, {'name': 'gyp', 'age': 25}, {'name': 'mama', 'age': 54}, {'name': 'baba', 'age': 55}]

111、 What is the output below

def extend_list(v,li=[]):
li.append(v)
return li
list1=extend_list(10)
list2=extend_list(123,[])
list3=extend_list('a')
print(list1) #[10,'a']
print(list2) #[123]
print(list3) #[10,'a']
print(list1 is list3) #True

112、 What is the output of the following code ?

l=['a','b','c','d','e']
print(l[10:]) #[]

113、 The following code executes the output

def func(m):
for k,v in m.items():
m[k+2]=v+2
m={
1:2,3:4}
l=m # Shallow copy 
l[9]=10
func(l)
m[7]=8
print("l:",l)
print("m:",m)
""" result =====》 An error is as follows : Traceback (most recent call last): File "E:/000 Code of the article /0000_2018 The old boy educated Shanghai python Off duty shift vip/python Interview questions / subject 3.py", line 11, in <module> func(l) File "E:/000 Blog post code /0000_2018 The old boy educated Shanghai python Off duty shift vip/python Interview questions / subject 3.py", line 5, in func for k,v in m.items(): RuntimeError: dictionary changed size during iteration #【 principle !】 When iterating over a list or dictionary , You cannot change the size of a list or dictionary !!!!!! """

114、#4 A comparison of two operations := section copy deepcopy

import copy
l1=[11,22,[33,44]]
l2=l1
l3=l1[:]
l4=copy.copy(l1)
l5=copy.deepcopy(l1)
l1[2].append(55)
print(l1) #[11, 22, [33, 44, 55]]
print(l2) #[11, 22, [33, 44, 55]]
print(l3) #[11, 22, [33, 44, 55]]
print(l4) #[11, 22, [33, 44, 55]]
print(l5) #[11, 22, [33, 44]]

115、Python Format the string in (% and format), What kind of , Why? ?
answer :1、 Simple use %, More than two values are generally used format
2、 If a variable is an ancestor when a string is formatted , utilize % Easy to make mistakes ; And in python3 It is recommended to use format format !

"""
# Control accuracy 
print('{:.2f}'.format(3.141592653)) #3.14
# Thousand separator 【 Money display 】
res='{:,}'.format(1234567890)
print(res) #1,234,567,890

116、 Generate the following list :[[0,0,0,0,0],[0,1,2,3,4],[0,2,4,6,8],[0,3,6,9,12]]

# Mode one 
list1=[]
for i in range(4):
tmp=[]
for j in range(5):
tmp.append(i*j)
list1.append(tmp)
print(list1) #[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12]]
# Mode two 
res=[[i*j for j in range(5)] for i in range(4)]
print(res) #[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12]]

117、 Decorator knowledge points

1. The principle of decorator and why to use decorator
2. The basic usage of decorators
3. Parameter decorator
4. How to handle the return value of the decorated function
5. Execution sequence of multiple decorators
6. Decorative ornament

118、os and sys What do they do

#os It is related to the system ,sys It is related to system interaction 
import os
BASE_DIR=os.path.abspath(__file__) # Take the absolute path of the current file 
base_dir=os.path.dirname(os.path.abspath(__file__)) # Take the path of the parent directory of the current file #E:\000 Code of the article \27
path=os.path.join(base_dir,"abc") # Splice one under the current parent directory abc Folder Directory 
path1=base_dir+"\\abc" # It is not recommended to use this hard coded form to splice paths 
import sys
sys.path.append() # Add a specified path to the currently running environment variable 
sys.argv # Return a list , The user is in cmd Parameters entered in 

119、 Three characteristics of object-oriented :
encapsulation 、 Inherit 、 polymorphic
120、 Talk about your understanding of object orientation ?
Object oriented understanding
Before I understand , Object oriented is a natural extension of the real world model , This is a kind of “ Everything is object ” Programming ideas . Any object in real life can be classified as one kind of thing , And every individual is an example of one kind of thing .
There are three characteristics of object-oriented , encapsulation 、 Inheritance and polymorphism .
Encapsulation is to abstract the attributes and behaviors of a class of things into a class , Privatize its properties , Act openly , Improve the privacy of data at the same time , Modularize the code . This makes the code more reusable .
Inheritance is to further abstract the common attributes and behaviors of a class of things into a parent class , And each subclass is a special parent class – There are behaviors and properties of the parent class , They also have their own unique behaviors and attributes . This extends the existing code block , Further improve the reusability of the code .
If encapsulation and inheritance are for code reuse , So polymorphism is for interface reuse . One of the great functions of polymorphism is to decouple – In order to decouple the inheritance of parent-child classes . If we say the relation of parent-child class in inheritance IS-A The relationship between , So the relationship between the interface and the implementation class HAS-A. Simply speaking , Polymorphism is allowing the parent class to refer to ( Or interface ) Pointing subclass ( Or implementation classes ) object . Many design patterns are based on object-oriented polymorphism design .
To sum up , If encapsulation and inheritance are the foundation of object orientation , Then polymorphism is the essence of object-oriented theory . To master polymorphism, you must first understand the interface , Only by fully understanding interfaces can polymorphism be better applied .

121、python What are the characteristics of inheritance in object-oriented ?

Advantages of inheritance :
1、 Build classes in the system , Avoid repetition .
2、 New classes are often based on existing classes , This can improve the reusability of the code .
The characteristics of inheritance :
1、 Construction of base class in inheritance (init() Method ) Will not be called automatically , It needs to be specifically called by itself in the construction of its derived class . Different from C#
2、 When a method of a base class is called , Need to prefix the class name of the base class , And you need to bring it self Parameter variable . Unlike calling ordinary functions in classes, you don't need to bring them up. self Parameters
3、Python Always find the method of the corresponding type first , If it cannot find the corresponding method in the derived class , It starts to look up one by one in the base class .( Find the called method in this class first , Cannot find to find in base class ).

122、 What are object-oriented depth first and breadth first ?

" Depth-first traversal " Consider recursion , Make the child node null as the condition for terminating recursion
" Breadth first traversal " Examine the structure of the queue , Eliminate parent nodes ( Outgoing queue , Print by the way ), Add child nodes ( In the queue ), When the number of elements in the queue is zero , Complete the traversal
python3 Do not distinguish between depth first and breadth first python2 Just distinguish between

123、 Object oriented super The role of ?

super() Function is used to call the parent class ( Superclass ) One way .
super It is used to solve the problem of multiple inheritance , It's OK to call the parent class method directly with the class name when using single inheritance , But if you use multiple inheritance , There's a search order involved (MRO)、 Repeated calls to ( Diamond inheritance ) And so on .
MRO Is the method parsing order table of the class , In fact, it is the order table when inheriting the parent method .

"""
class Person():
def __init__(self,name,age):
self.name=name
self.age=age
class Male(Person):
def __init__(self,name,age,location):
super().__init__(name,age)
self.location=location
man=Male('psy',18,'nuist')

124、 To write Python Script , analysis xx.log file , Count the number of visits by domain name

import re
#1 Read text 
with open('xx.log','r',encoding='utf-8')as f:
data=f.read()
#2 Get domain name 
res=re.findall("https://(.*?)/",data) # Returns a list of 
#3 Statistics 
res_dic={
}
for item in res:
if item not in res_dic:
res_dic[item]=1
else:
res_dic[item] +=1
#4 Sort 
res2=sorted(res_dic,key=lambda x:res_dic[x],reverse=True)
for key in res2:
print(res_dic[key],key)

125、 database 【 Design table structure ( How to create foreign key constraints ?!)】
Design The book management system Table structure :
- book (pk Title )
- author (pk full name )
- Press. (pk Publisher name Address )
analysis :
A book can only be published by one publisher 【 For one more , Multiple publishers correspond to one book 】》 Set up foreign keys , Foreign keys are placed in “ One ” In your watch , Everyone can use
A book can have more than one author , One author can also write more than one book 【 Many to many 】
》 Through the third table , Connect with the book and the author respectively

""" """MySQL Statements for creating tables in
CREATE TABLE book(
id INT PRIMARY KEY AUTO_INCREMENT,title VARCHAR(64),publisher_id INT,
FOREIGN KEY (publisher_id) REFERENCES publisher(id));
CREATE TABLE author(
id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(32));
CREATE TABLE book2author(
id INT PRIMARY KEY AUTO_INCREMENT,book_id INT,author_id INT,
FOREIGN KEY (book_id) REFERENCES book(id),
FOREIGN KEY (author_id) REFERENCES author(id));
CREATE TABLE publisher(
id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(64),address VARCHAR(255));
"""

Ali simulated written test questions :
subject :
The biggest in the country web Site statistics service provider CNZZ, Monitor that a customer site is updating its homepage advertising space , The home page has n An advertising , Yes 3 A kind of advertisement (A,B,C),A Advertising takes up 1 An advertising ,B Advertising takes up 2 An advertising ;C Advertising takes up 3 individual ; Advertisements are linked together , Any combination of , To ensure the beauty of the home page ,A The left and right sides of advertisements cannot appear A advertisement ,B and C There is no limit .
How many kinds of advertising space layout schemes are there on the home page of the site .
Input :n An advertising
Output :z Three layout schemes

Compiler Version : Python 2.7.6
Please use standard output (sys.stdout); Graphics disabled 、 file 、 The Internet 、 System related operations , Such as Process , httplib , os; Indent can be used tab、4 A space or 2 A space , But only one of them can be chosen , It is not allowed to mix several ; If you use sys.stdin.readline, Because there will be a line break by default , So we need to strip(’ ') Intercept ; It is recommended to use raw_input()
The time limit : 3S (C/C++ Other languages are : 5 S) Memory limit : 128M (C/C++ Other languages are : 640 M)
Input :
Input :n An advertising ,n For more than 0 The positive integer
Output :
Output :z Three layout schemes ,z For more than 0 The positive integer
Input example :
Input example :3
Output example :
Output example :3

"""
# Code 
def cut(n,isA):
if n<=0:
return 0 # When the advertising space is 0 when , return 0
if n==1:
return 1 # The advertising space is 1 when , return 1 A
if n==2:
return 1 # The advertising space is 2 when , return 2 B
if n==3:
if isA:
return 2
else:
return 3 # The advertising space is 3 when , return 2 AB BA C
if isA:
return cut(n-2,False)+cut(n-3,False)
else:
return cut(n-1,True)+cut(n-2,False)+cut(n-3,False)
print(cut(6,False))

Conclusion

Found a very easy to use brush question website ! Let's work together ! come on. !!!
The difficulty of the topic can be chosen by oneself
Program the answer online ,( You can also check the answers by yourself ) Very convenient
Programmers brush question artifact website Click the link to register and you can brush the question
I wish you all a satisfactory job as soon as possible


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