Geek University Python Advanced Training Camp 2.0 is a new upgrade

Use the slicing operation to implement a trim() function to remove spaces at the beginning and end of the string, and be careful not to call the strip() method of str. Correct
solution 1:

def trim(s):
while s[:1] == ’ ':
s = s[1:]
while s[-1:] == ’ ':
s = s[:-1]
return s
正解2:

def trim(s):
if s[:1] == '':
s = trim(s[1:])
if s[-1:] =='':
s = trim(s[:-1])
Return s is
easy to write wrong method:

def trim(s):
while s[0] == '':
s = s[1:]
while s[-1] =='':
s = s[:-1]
return s
Explanation: When s=' ', s[0] and s[-1] will report IndexError: string index out of range, but s[:1]) and s[-1:] will not.

Please design a decorator that can be applied to any function and print the execution time of the function.

-- coding: utf-8 --

import time, functools
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
time0 = time.time()
ret = fn(*args, **kw)
time1 = time. time()
print('%s executed in %s ms'% (fn. name , time1-time0))
return ret What is the essence of the
return wrapper
decorator? In other words, why the decorator has to write two levels of nested functions, and the inner function has completely realized the function of decoration. Why not directly use the inner function name as the decorator name?

Answer: The decorator is to decorate the original function into a new function and return the higher-order function of the function itself

The limitation of multi-threading under python and the way of passing parameters in multi-process

Python multithreading has a global interpreter lock. This lock means that only one thread can use the interpreter at any one time. It means running multiple programs with a single CPU. Everyone uses it in turn. It's called "concurrency", not "parallel".

To share data between multiple processes, you can use multiprocessing.Value and multiprocessing.Array

The difference between python multithreading and multiprocess:

On the UNIX platform, when a process terminates, the process needs to be called wait by its parent process, otherwise the process becomes a zombie process (Zombie). Therefore, it is necessary to call the join() method on each Process object (actually equivalent to wait). For multithreading, since there is only one process, there is no such necessity.

Multiple processes should avoid sharing resources. In multithreading, we can easily share resources, such as using global variables or passing parameters. In the case of multiple processes, since each process has its own independent memory space, the above method is not appropriate. At this point, we can share resources by sharing memory and Manager. But doing so increases the complexity of the program and reduces the efficiency of the program because of the need for synchronization.

Please write a piece of Python code to delete duplicate elements in a list

l = [1,1,2,3,4,5,4]
list(set(l))
[1, 2, 3, 4, 5]
or
d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
uses the map() function to change the irregular English names entered by the user into capitalized first letters and other canonical names in lowercase. Input: ['adam','LISA','barT'], output: ['Adam','Lisa','Bart']:
def normalize(name):
return name[0].upper()+name[ 1:].lower()

def normalizeList(inputlist):
return list(map(normalize, inputlist))

How does Python manage memory?
  http://developer.51cto.com/art/201007/213585.htm
  Python refers to a memory pool (memory pool) mechanism, that is, the Pymalloc mechanism (malloc:n. allocate memory), which is used to manage applications for small blocks of memory And release
the concept of memory pool:
  When creating a large number of objects that consume small memory, frequent calls to new/malloc will cause a large amount of memory fragmentation and reduce efficiency. The concept of the memory pool is to apply for a certain amount in the memory in advance, and memory blocks of equal size are reserved for spare. When there is a new memory demand, the memory is allocated from the memory pool to this demand first, and then a new one is applied when it is not enough. RAM. The most significant advantage of this is that it can reduce memory fragmentation and improve efficiency.
There are many ways to implement the memory pool, and the performance and scope of application are also different.
The memory management mechanism in
  python- Pymalloc: The memory management mechanism in python has two sets of implementations, one is for small objects, that is, when the size is less than 256bits, pymalloc will apply for memory space in the memory pool; when it is greater than 256bits, then Will directly execute the new/malloc behavior to apply for memory space.
  Regarding the release of memory, when the reference count of an object becomes 0, python will call its destructor. During destructuring, a memory pool mechanism is also used, and the memory from the memory pool will be returned to the memory pool to avoid frequent release actions.

Explain the and-or syntax of python
http://www.kuqin.com/diveinto_python_document/apihelper_andor.html is
similar to the C expression bool? A: b, but bool and a or b, when a is false, it will not look like The C expression bool? A: b works the same.
The and-or technique should be encapsulated into a function:

def choose(bool, a, b):
return (bool and [a] or [b])[0]
Because [a] is a non-empty list, it will never be false. Even if a is 0 or'' or other false value, the list [a] is true because it has one element.

how do I iterate over a sequence in reverse order
for x in reversed(sequence):
… # do something with x…
If it is not a list, the most common but slower solution is:

for i in range(len(sequence)-1, -1, -1):
x = sequence[i]

How does Python implement singleton mode? How to implement the other 23 design patterns in python?

How to copy an object in Python?
https://www.yuque.com/dangxianyuyudaoniu/kclb/2020
The copy module in the standard library provides two methods to implement copy. One method is copy, which returns an object
with the same content as the parameter. Using the deepcopy method, the object The attributes in are also copied

What is the difference between search() and match() in Python?
The match() function only detects whether the RE matches at the beginning of the string, search() scans the entire string for a match, that is to say, match() returns only if the match is successful at position 0, if it is not at the beginning of the match. , Match() returns none

There are two sequences a, b, the size is n, the values ​​of the sequence elements are arbitrary integers, and they are disordered;
requirements: by exchanging the elements in a, b, make [the sum of the elements of a sequence] and [the sum of the elements of the sequence b] ] Is the smallest difference.

Calculate the sum of a and b sequences respectively;
find the half of the difference between the sum of a sequence and the sum of b sequence and record it as half;
find a difference between the element max in a sequence with a large sum and a sequence with a small sum The element closest to half is marked as min; just
interchange max and min.
Describe the concept of metaclasses. Does Python have an interface? What are the similarities and differences between metaclasses and Java interfaces?
There is no interface type in python, and the definition of interface class (abstract class) is just an artificial stipulation, which is self-constrained in the programming process.
Metaclasses are templates for classes, and they focus on helping create classes. The interface is to provide ideas and implement them later.

Guess you like

Origin blog.csdn.net/weixin_52772147/article/details/112824906