python Basics (interview)

Differences between get post requests

1. post Request security higher than get. get Request to expose parameters directly to url Up, post Request to hide parameters
		To pass a password post

2. get The request has a limit on the length of the data, url The maximum length of is 2048 characters. post unlimited
		When transferring large amounts of data, use post
3. get Only delivery allowed ASCII Character, and post Any character can be passed
		
4. http Semantic stipulation get Get data, post Submit data

Why use get for so many advantages of post

1. get Is to get data from the server, post Is to transfer data to the server

The difference between xreadlines and readlines in file operation;

# readlines (common)
	Is to read all the contents of the file into memory and parse it into a file list,When the file volume is large, it needs to occupy a lot of memory
	
# xreadlines
	Directly return a iter(file)Iterator, in python2.3 After that, it has been used directly without pushing the key for Iteration object

List common values whose Boolean value is False

0  	[]  	 ()  		{}  	  ''      False  None
 Null list 	Empty tuple		Empty dictionary		Empty string

Difference between is and = =

is The comparison is id
== The comparison is the value

Existing dictionary dicts = {'a': 24, 'b': 52, 'c': 12, 'k': 33} sorted by value

dicts.items()		Returns a list of key value pairs
# dict_items([('a', 24), ('b', 52), ('c', 12), ('k', 33)])

new_dicts = sorted(dicts.items key=lambda x:x[1])
print(new_dicts)
# [('c', 12), ('a', 24), ('k', 33), ('b', 52)]

Please flip the string

s = '123456'
print(s[::-1])

Please sort the elements in the list from large to small

l = [{'name': 'a', 'age': 21}, {'name': 'c', 'age': 11}, {'name': 'b', 'age': 25}]
print(l[1])
# {'name': 'c', 'age': 11}
print(l[1]['age'])
# 11
new_l = sorted(l, key=lambda x: x['age'], reverse=True)	# True descending order
print(new_l)
# [{'name': 'b', 'age': 25}, {'name': 'a', 'age': 21}, {'name': 'c', 'age': 11}]

String formatting

name = 'Zang San'
age = 11
s1 = '%s Hello' % name
s2 = '{} Hello{}'.format(name, age)
s3 = f'{name} Hello {age}'
print(s1)		# Hello, Zang San
print(s2)		# Hello Zang San 11
print(s3)		# Hello Zang San 11

What does the following code output

l = [1, 12, 2, 3, 2]
print(l[10:])
# []
'''
Code output[],Will not produce indexerror Wrong.
If you try to get l[10]		,An error will be reported
'''

Write a list generating formula to produce an equal deviation with a tolerance of 10

# Tolerance is 10
print([i*10 for i in range(5)])			# [0, 10, 20, 30, 40]

# The common ratio is 2
print([2**i for i in range(5)])			# [1, 2, 4, 8, 16]

Delete duplicate elements in the list

l1 = [1, 2, 3, 43, 21, 1, 1]
l2 = list(set(l1))
print(l2)
# [1, 2, 3, 43, 21]

Find out the same elements and different elements in the two lists

l1 = [1, 12, 2, 3, 2]
l2 = [1, 2, 3, 43, 21, 1, 1]

set1 = set(l1)
set2 = set(l2)
# Same element (intersection)
print(set1&set2)			# {1, 2, 3}
# Different elements (Union)
print(set1^set2)			# {21, 43, 12}

Enumerate strings. List. Tuples. Common methods for fields

What is reflection? And application scenarios

python deep copy shallow copy

python garbage collection mechanism

Disrupt an ordered list

import randomrandom.shuffle(list1)

Take 10 numbers randomly from 0-99, and it is required not to repeat

print([x*x for i in range(1,11)])

Introduce try- except

How python throws exceptions. Capture. handle

Maximum number of layers of python recursion

998

Difference between list derivation and generator expression

print([i % 2 for i in range(1, 10)])# [1, 0, 1, 0, 1, 0, 1, 0, 1]print((i % 2 for i in range(1, 10)))# <generator object <genexpr> at 0x000001EFD6F81B48>

closure

Implement a decorator to limit the frequency at which the function is called, once every 10 seconds

On the understanding of closure

Is the parameter passed by value or reference when python function is called

Conditions for stopping recursive functions

What is mro

What is c3 algorithm

Enumerate special methods that are only double underlined in object-oriented

Difference between double line and single underline

with usage

Advantages and applications of singleton mode

When serializing json, Chinese is converted to Unicode by default. What if you want to keep Chinese

<. > and <.? > difference

How to judge whether a mailbox is legal

Basic questions

How to exchange the values of two variables

# python Special grammar a,b = b, a# Other languages int a=5,int b=3,1 Establish the intermediate variable method int temp,temp = a,b = a,b = temp,2 Addition and subtraction a = a+bb = a-b 		 (a+b-b 	) a = a-b 		 (a+b-(a-b))3.  Exclusive or method a = a^bb = a^ba = a^b

How to splice two strings efficiently

1. use + To splice strings. If the spliced strings are multiple( n )One, python The interpreter will apply n-1 A memory space and then copy it. two. use		.join(list)	Memory space was used only once.

list = [a,a,a,1,2,3,4,5,A,B,C] extract "12345"

1. ergodic list = ['a','a','a',1,2,3,4,5,'A','B','C']a = []for i in list:    if type(i) == int:        a.append(i)       2. Decompression assignment a,b,c,*aa,b,c,d = my_listprint(aa)

What is a metaclass

search and match knowledge points in python

search and match All in re Module. one. match Only the beginning of the string is matched. If the beginning does not conform to the regular expression, the matching fails and the function returns None2. search Matches the entire string until a match is found.

python deep and shallow copy

1. Shallow copy does not copy sub objects, so the original object is changed and its sub objects are also changed. 2. Deep copy copies the child object, and the original object will not change itself. 
# Shallow copy l1 = [1,2,3]l2 = copy.copy(l1)l1[0] = 'hello'print(l1,l2)# ['hello',2,3] [1,2,3]Because list 1 was originally in a space, through copy Listing 2 opens up a new space and copies the elements of Listing 1. So no matter how you modify list 1, list 2 will not change. l3 = [[1,2,3],[4,5,6]]l4 = copy.copy(l3)l3[0][0] = 'hello'print(l3,l4)# [['hello',2,3][4,5,6]] [['hello',2,3][4,5,6]]l3 The outermost layer points to a memory address, and the inner layer l3[0] l3[1] Point to a memory address respectively. Shallow copy only copies the memory address of the outer layer, so change the data of the inner layer, l4 Will also change.# Deep copy L5 = [[11,22,33] [44,55,66]] L6 = copy Deep copy (L5) print (l5,l6) copies the memory address of the inner layer, so there is no change in modifying L5 and L6

python deep and shallow copy https://www.bilibili.com/video/BV1eE411P7Vh?from=search&seid=14542617443564894000&spm_id_from=333.337.0.0

Multithreading

python memory management

python filter method

filter Like map,reduce,apply,zip And so on are built-in functions, using c Language implementation, powerful, used for filtering and functions func()Mismatched values. Two parameters. First parameter: function perhaps None Second parameter: sequence ,sequence filter Filter out func(Single parameter function) Returns True Value of. func It can also be used lambda If it is empty, the return sequence is True Value of.# When in use: you can convert the filter object into list, tuple and collection, or use the for loop to traverse
def func(x):    return x>5l = [3,4,5,6,7,8]a = filter(func,l)print(a)print(list(a))# <filter object at 0x000001C064155488># [6, 7, 8]li = [1, 2, '', []]b = filter(None, li)print(list(b))# [1,2]

reduce() function

Standard library functools Functions in reduce()A function that accepts two parameters can be applied to a sequence or iterator in an iterative cumulative manner.# You can specify an initial value
from functools import reducea = [1, 2, 3]l = reduce(lambda x, y: x + y, a, 6)print(l)# 12

map function

map Put a function func Map to each element of the sequence in turn and return an iteratable map Object as a result
m = map(lambda x:x+1,[1,2,3,4])print(m)print(list(m))# <map object at 0x000002B805F4F248># [2, 3, 4, 5]

Function signature

# When we're writing functions, for example a Is a string,Write like this a. There will be no hint def func1(a):    a.#  Writing this will prompt all methods of the string def func2(a:str):    a.    # Specify return value def func2(a:str,b:int)->str:    pass# No return value def func2 (A: STR, B: int) - > none: Pass

Regular expression re sub

Find one thing from a string str and replace it with another

s = re.sub(pattern='Zhang San',repl='zs',string=l,flags=re.S)print(s)pattern		String to replace repl		replace with xxstring		String to find flags		Matching pattern re.S Full text matching# Remove all spaces re.sub(pattern=r'\s+',repl='',string=l,flags=re.S)        # Another way of writing B = re compile(r'\s+',flags = re.S)re. sub(pattern=b,repl='',string=l)

re.search()

re.findall

pattern = re.compile()url = pattern.findall(str)

Query replacement of string

python of find and replace function find If found, return the subscript (if there are multiple, return the subscript of the first one). If not found, return-1
string = 'life is short, I use python'print(string.find('file'))print(string.find('life'))print(string.replace('short', 'long'))# -1# 0# life is long, I use python

Given a list, disrupt

shuffle function

import randoml = [1, 2, 3, 5, 6, 7, 8]random.shuffle(l)print(l)# [7, 8, 2, 5, 6, 1, 3]

Decorator

python implements singleton mode

Implement a Fibonacci sequence generator

The first two items are 0 and 1, and each of the following items is equal to the sum of the first two items.

def fib(n):    a, b = 0, 1    for i in range(n):        a, b = b, a + b        yield adef main():    for val in fib(10):        print(val)if __name__ == '__main__':    main()

Use string splicing to achieve subtitle scrolling effect

import osimport timedef main():    content = 'xxx of python Interview set'    while True:        os.system('cls')        print(content)        time.sleep(0.2)        content = content[1:] + content[0]if __name__ == '__main__':    main()

Design a function to return the suffix of the given file name

Examine regular expressions

def get_suffix(filename,has_dot=False):    '''    filename:file name    has_dot : Whether the suffix returned is dotted    '''    pos = filename.rfind('.')    # Find the index of the rightmost point if 0 < POS < len (filename) - 1: index = POS if has_ dot else pos+1        return filename[index:]    else:        return ''print(get_suffix('1.x.txt'))

Variable length position parameter * args

def func(*args):    print(args)    print(type(args))if __name__ == '__main__':    func(1,2,'lkx')    print('-'*10)    func('9',10,'ljh')  (1, 2, 'lkx')<class 'tuple'>----------('9', 10, 'ljh')<class 'tuple'>

Variable length keyword parameter * * kwargs

def func2(**kwargs):    print(type(kwargs))if __name__ == '__main__':    func2(a=1, b='122')    <class 'dict'>

Decorator

#  The following is a function for finding prime numbers import time# Decorator def is_prime(num):    if num<2:        return False    elif num == 2:        return True    else:        for i in range(2, num):            if num%i == 0:                return False        return True# Output all prime numbers between 2-1000 def prime_nums():    t1 = time.time()    for i in range(2,1000):        if is_prime(i):            print(i)    t2 = time.time()    print(t2-t1)prime_nums()

The above code looks chaotic, including both the logic part and the timing part

If there are multiple functions that need timing, it is very troublesome,

Use decorator

def display_time(func):    def wapper():        t1 = time.time()        func()        t2 = time.time()        print(t2 - t1)    return wapperdef is_prime(num):    if num < 2:        return False    elif num == 2:        return True    else:        for i in range(2, num):            if num % i == 0:                return False        return True# Output all prime numbers @ display between 2-1000_ timedef prime_nums():    for i in range(2, 1000):        if is_ prime(i):            print(i)prime_nums() run prime_ When the num () function, it first runs the decorator display_time, run prime only when func()_ nums()

If Prime_ What if the num () function has a return value

Record the return value and put it into res. res will receive func(), and finally return

def display_time(func):    def wapper():        t1 = time.time()        res = func()        t2 = time.time()        print(t2 - t1)        return res    return wapperdef is_prime(num):    if num < 2:        return False    elif num == 2:        return True    else:        for i in range(2, num):            if num % i == 0:                return False        return True# Output all prime numbers @ display between 2-1000_ timedef prime_ nums():    count = 0    for i in range(2, 1000):        if is_ prime(i):            count = count + 1    return countcount = prime_ nums()print(count)

The problem now is that we write 2-1000 in the function, if we want to write the calculated number in

prime_ What about nums()

We need to add parameters to the decorator wapper, but if we don't know how many to add, we can use * args

# z Decorator def display_time(func):    def wapper(*args):        t1 = time.time()        res = func(*args)        t2 = time.time()        print(f'total time:{t2-t1} s')        # print('total time:{:.4} s'.format(t2-t1))        return res    return wapperdef is_prime(num):    if num < 2:        return False    elif num == 2:        return True    else:        for i in range(2, num):            if num % i == 0:                return False        return True# Output all prime numbers @ display between 2-1000_ timedef prime_ nums(maxnum):    count = 0    for i in range(2, maxnum):        if is_ prime(i):            count = count + 1    return countcount = prime_ nums(1000)print(count)

Keywords: Python Interview

Added by Hodo on Mon, 21 Feb 2022 17:45:57 +0200