21 classic Python interview questions [recommended collection]

1. How does Python implement the singleton mode?

Python has two ways to implement singleton mode. The following two examples use different ways to implement singleton mode:

1.

class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
print MyClass()
print MyClass()
  1. Use decorator to implement singleton mode

def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:

2: What is a lambda function?

Python allows you to define a small single-line function. The form of defining a lambda function is as follows: labmda parameters: expression lambda function returns the value of the expression by default. You can also assign it to a variable. The lambda function can accept any number of parameters, including optional parameters, but there is only one expression:

>>> g = lambda x, y: x*y
>>> g(3,4)
12
>>> g = lambda x, y=0, z=0: x+y+z
>>> g(1)
1
>>> g(3, 4, 7)
14

It is also possible to use the lambda function directly without assigning it to a variable:

>>> (lambda x,y=0,z=0:x+y+z)(3,5,6)
14

If your function is very simple, with only one expression and no commands, consider lambda functions. Otherwise, you still have to define the function. After all, the function does not have so many restrictions.

3: How does Python perform type conversion?

Python provides built-in functions to convert variables or values ​​from one type to another. The int function can convert a numeric string conforming to a mathematical format into an integer. Otherwise, an error message is returned.

>>> int(”34″)
34
>>> int(”1234ab”) #不能转换成整数
ValueError: invalid literal for int(): 1234ab

The function int can also convert a floating-point number to an integer, but the decimal part of the floating-point number is truncated.

>>> int(34.1234)
34
>>> int(-2.46)
-2

The function °oat converts integers and strings into floating-point numbers:

>>> float(”12″)
12.0
>>> float(”1.111111″)
1.111111

The function str converts numbers into characters:

>>> str(98)
‘98′
>>> str(”76.765″)
‘76.765′

Integer 1 and floating point 1.0 are different in python. Although their values ​​are equal, they belong to different types. The storage form of these two numbers in the computer is also different.

Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
For these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code!
QQ group: 810735403

 

4: How does Python define a function

The definition of the function is as follows:

def <name>(arg1, arg2,… argN):
<statements>

The name of the function must also start with a letter and can include the underscore "", but you cannot define Python keywords as the name of the function. The number of statements in the function is arbitrary, and each statement has at least one space indentation to indicate that the statement belongs to the function. Where the indentation ends, the function ends naturally.
The following defines a function to add two numbers:

>>> def add(p1, p2):
print p1, “+”, p2, “=”, p1+p2
>>> add(1, 2)
1 + 2 = 3

The purpose of the function is to hide some complex operations to simplify the structure of the program and make it easy to read. Before the function is called, it must be defined first. You can also define a function inside a function, and the internal function can only be executed when the external function is called. When the program calls a function, it goes to execute the statement inside the function. After the function is executed, it returns to the place where it left the program and executes the next statement of the program.

5: How does Python manage memory?

Python's memory management is taken care of by the Python interpreter. Developers can free themselves from memory management affairs and devote themselves to the development of application programs, so that the development of programs has fewer errors, more robust programs, and shorter development cycles.

6: How to iterate a sequence in reverse order?

how do I iterate over a sequence in reverse order

If it is a list, the fastest solution is:

list.reverse()
try:
for x in list:
“do something with x”
finally:
list.reverse()

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]
<do something with x>

7: How to realize the conversion between tuple and list in Python?

The function tuple(seq) can convert all iterable sequences into a tuple, with the same elements and the same ordering.
For example, tuple([1,2,3]) returns (1,2,3), tuple('abc') returns ('a'.'b','c'). If the parameter is already a tuple, The function does not make any copy but directly returns the original object, so it is not very expensive to call the tuple() function when you are not sure whether the object is a tuple.
The function list(seq) can convert all sequences and iterable objects into a list, with the same elements and the same sorting.
For example, list([1,2,3]) returns (1,2,3), list('abc') returns ['a','b','c']. If the parameter is a list, she will make a copy like set[:]

8: Python interview questions: Please write a piece of Python code to delete duplicate elements in a list

You can reorder the list first, and then start scanning from the end of the list, the code is as follows:

if List:
List.sort()
last = List[-1]
for i in range(len(List)-2, -1, -1):
if last==List[i]: del List[i]
else: last=List[i]

9: Interview questions for Python file operations

  1. How to delete a file with Python?
    Use os.remove(filename) or os.unlink(filename);

  2. How does Python copy a file?
    The shutil module has a copyfile function to realize file copy

10: How to generate random numbers in Python?

The standard library random implements a random number generator. The example code is as follows:

import random
random.random()

It will return a random floating point number between 0 and 1.

11: How to send mail with Python?

You can use the smtplib standard library.
The following code can be executed on a server that supports SMTP listener.

import sys, smtplib
fromaddr = raw_input(”From: “)
toaddrs = raw_input(”To: “).split(’,')
print “Enter message, end with ^D:”
msg = ”
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# 发送邮件部分
server = smtplib.SMTP(’localhost’)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

12: How to copy an object in Python?

Generally speaking, you can use the copy.copy() method or copy.deepcopy() method. Almost all objects can be copied.
Some objects can be copied more easily. Dictionaries have a copy method:

newdict = olddict.copy()

13: Is there a tool that can help find python bugs and perform static code analysis?

Yes, PyChecker is a static analysis tool for python code. It can help find bugs in python code and warn
about the complexity and format of the code. Pylint is another tool that can perform coding standard checks.

14: How to set a global variable in a function?

The solution is to insert a global declaration at the beginning of the function:

def f()
global x

15: When matching HTML tags with Python, what is the difference between <.> and <.?>?

When repeatedly matching a regular expression, such as <.*>, when the program executes the matching, the largest matching value will be returned.
For example:

import re
s = ‘<html><head><title>Title</title>’
print(re.match(’<.*>’, s).group())

Will return a match instead of
and

import re
s = ‘<html><head><title>Title</title>’
print(re.match(’<.*?>’, s).group())

It will return
<.> This kind of matching is called greedy matching <.?> is called non-greedy matching

16: 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.
For example:

print(re.match(’super’, ’superstition’).span())

Will return (0, 5)
and

print(re.match(’super’, ‘insuperable’))

Return None
search() will scan the entire string and return the first successful match.
For example:

print(re.search(’super’, ’superstition’).span())

Returns (0, 5)

print(re.search(’super’, ‘insuperable’).span())

Returns (2, 7)

17: How to use Python to query and replace a text string?

You can use the sub() method to query and replace. The format of the sub method is: sub(replacement, string[, count=0])
replacement is the text
to be replaced, string is the text to be replaced,
count is an optional parameter , Refers to the maximum number of replacements
Example:

import re
p = re.compile(’(blue|white|red)’)
print(p.sub(’colour’,'blue socks and red shoes’))
print(p.sub(’colour’,'blue socks and red shoes’, count=1))

Output:

colour socks and colour shoes
colour socks and red shoes

The subn() method performs the same effect as sub(), but it returns a two-dimensional array, including the new string after replacement and the total number of replacements.
For example:

import re
p = re.compile(’(blue|white|red)’)
print(p.subn(’colour’,'blue socks and red shoes’))
print(p.subn(’colour’,'blue socks and red shoes’, count=1))

Output

(’colour socks and colour shoes’, 2)
(’colour socks and red shoes’, 1)

18: Tell me about the usage and function of except?

Python's except is used to catch all exceptions. Because every error in Python throws an exception, every program error is treated as a runtime error.
Here is an example of using except:

try:
foo = opne(”file”) #open被错写为opne
except:
sys.exit(”could not open file!”)

Because this error is caused by open being spelled as opne and then caught by except, it is easy to not know what went wrong when debugging the program.
Here is a better example:

try:
foo = opne(”file”) # 这时候except只捕获IOError
except IOError:
sys.exit(”could not open file”)

19: What is the function of the pass statement in Python?

The pass statement does nothing. It is generally used as a placeholder or to create a placeholder program. The pass statement does not perform any operations, such as:

while False:
pass

Pass is usually used to create the simplest class:

class MyEmptyClass:
pass

Pass is also often used as TODO in the software design stage to remind the implementation of the corresponding implementation, such as:

def initlog(*args):
pass #please implement this

20: Tell me about the usage of range() function in Python?

If you need to iterate a sequence of numbers, you can use the range() function, which can generate an arithmetic series.
For example:

for i in range(5)
print(i)

This code will output five numbers 0, 1, 2, 3, 4.
Range(10) will generate 10 values. You can also make range() start from another number, or define a different increment, or even a negative number. Increment
range(5, 10) Five numbers from 5 to 9
range(0, 10, 3) The increment is three, including the four numbers
0,3,6,9 range(-10, -100, -30 ) The increment is -30, including -10, -40, -70.
You can use range() and len() together to iterate an index sequence.
For example:

a = ['Nina', 'Jim', 'Rainman', 'Hello']
for i in range(len(a)):
    print(i, a[i])

21: There are two sequences a, b, the size is n, the value of the sequence element is arbitrary integer,

Disordered; requirement: By exchanging the elements in a and b, the difference between [sum of elements in sequence a] and [sum of elements in sequence b] is minimized.
Combine the two sequences into one sequence, and sort, as the sequence Source

Take out the largest element Big, the second largest element Small

Divide equally on the remaining sequence S[:-2] to get the sequence max, min

Add Small to the max sequence, increase Big to the min sequence, recalculate the sum of the new sequence, and the large sum is max and the small one is min.

Python code

def mean( sorted_list ):
if not sorted_list:
return (([],[]))
big = sorted_list[-1]
small = sorted_list[-2]
big_list, small_list = mean(sorted_list[:-2])
big_list.append(small)
small_list.append(big)
big_list_sum = sum(big_list)
small_list_sum = sum(small_list)
if big_list_sum > small_list_sum:
return ( (big_list, small_list))
else:
return (( small_list, big_list))
tests = [   [1,2,3,4,5,6,700,800],
[10001,10000,100,90,50,1],
range(1, 11),
[12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1]
]
for l in tests:
l.sort()
print
print “Source List:    ”, l
l1,l2 = mean(l)
print “Result List:    ”, l1, l2
print “Distance:    ”, abs(sum(l1)-sum(l2))
print ‘-*’*40

Output result

Source List:    [1, 2, 3, 4, 5, 6, 700, 800]
Result List:    [1, 4, 5, 800] [2, 3, 6, 700]
Distance:       99
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 50, 90, 100, 10000, 10001]
Result List:    [50, 90, 10000] [1, 100, 10001]
Distance:       38
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Result List:    [2, 3, 6, 7, 10] [1, 4, 5, 8, 9]
Distance:       1
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 1, 2, 3, 29, 30, 210, 232, 12311, 12312]
Result List:    [1, 3, 29, 232, 12311] [1, 2, 30, 210, 12312]
Distance:       21
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Here I still want to recommend the Python development exchange learning (qq) group I built by myself : 810735403 , all students in the group are learning Python development. If you are learning Python, you are welcome to join. Everyone is a software development party and share it from time to time. Dry goods (only related to Python software development), including a copy of the latest Python advanced materials and advanced development tutorials compiled by myself in 2021, welcome to advanced and friends who want to go deep into Python!

Guess you like

Origin blog.csdn.net/XIe_0928/article/details/113105557