[Python] Interview basic knowledge points

Python basic test 100 questions

1. The difference between interpreted and compiled languages

Compiled language: Compile all prepared source programs into binary executable programs. Then, you can run this program directly. Such as: C, C++
interpreted language: translate one sentence of the completed source program, and then execute one sentence until the end! Such as: Python,
(Java is a bit special, java program also needs to be compiled, but it is not directly compiled called machine language, but compiled called bytecode, and then the bytecode is executed in an interpreted way.)

2. Common methods of data types

One, format formatting function

The str.format() function is a format string function, this function can quickly process various strings.
It uses {} and: instead of %.
String formatting uses the format() method. The basic format used is:
<template string>.format(<comma-separated parameters>) After
calling the format() method, a new string will be returned, with parameters numbered starting from 0 .

1、通过关键字

print('{name}在{option}'.format(name="谢某人",option="写代码"))
结果:谢某人在写代码 

2、通过位置

print('name={} path={}'.format('zhangsan', '/')
结果:name=zhangsan path=/


print('{1}在{0}'.format('写代码','谢某人'))
或
print('{0}在{1}'.format('谢某人','写代码'))
结果:谢某人在写代码

3、填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度

print('{:^30}'.format("zhangsan")) # 居中
print('{:>30}'.format("zhangsan")) # 右对齐
print('{:<30}'.format("zhangsan")) # 左对齐
30:字段长度(最左到最右之间的长度)

Insert picture description here

4、精度控制  :.nf

print('{:.2f}'.format(3.14159))
结果:3.14
保留两位小数,两位后四舍五入

print('{:.5f}'.format(3.14))
结果:3.14000
保留5位小数,不足补0.

进制转化,b o d x 分别表示二、八、十、十六进制

print('{:b}'.format(20))
print('{:o}'.format(20))
print('{:d}'.format(20))
print('{:x}'.format(20))
结果:

10100
24
20
14 

5、 千位分隔符::,

print('{:,}'.format(100000000))
print('{:,}'.format(123456.123456))
结果:

100,000,000
123,456.123456

Two, join function

It can be used to concatenate strings, connect the elements in strings, tuples, and lists with specified characters (separators) to generate a new string.

list1 = ['1','2','3','4']  
s = "-"
s = s.join(list1) 
print(s) 

输出:
1-2-3-4

用空字符连接

list1 = ['g','e','e','k', 's']  
print("".join(list1)) 
输出:

geeks

Three, replace function

String.replace(old,new,count) replace old characters in the string with New characters, and count is the number of replacements

mystr4 = ‘luobodazahui-haha’
print(mystr4.replace(‘haha’, ‘good’))

output

luobodazahui-good

Four, split function

Cut the string to get a list.

mystr5 ='luobo,dazahui good'

Split by spaces
print(mystr5.split())
split by h
print(mystr5.split('h'))
split by commas
print(mystr5.split(','))
output

['luobo,dazahui','good']
['luobo,daza','ui good']
['luobo','dazahui good']
list:

  1. slice

Same string

  1. append 和 extend

Add elements to the list China

mylist1 = [1, 2]
mylist2 = [3, 4]
mylist3 = [1, 2]
mylist1.append(mylist2)
print(mylist1)
mylist3.extend(mylist2)
print(mylist3)
outout

[1, 2, [3, 4]]
[1, 2, 3, 4]

  1. Delete element

del: delete according to the subscript
pop: delete the last element
remove: delete according to the value of the element

mylist4 = [‘a’, ‘b’, ‘c’, ‘d’]
del mylist4[0]
print(mylist4)
mylist4.pop()
print(mylist4)
mylist4.remove(‘c’)
print(mylist4)
output

[‘b’, ‘c’, ‘d’]
[‘b’, ‘c’]
[‘b’]

  1. Element sorting

sort: rearrange the list in a specific order, the default is from small to large, the parameter reverse=True can be changed to reverse order, from large to small.

reverse: Reverse the list.

mylist5 = [1, 5, 2, 3, 4]
mylist5.sort()
print(mylist5)
mylist5.reverse()
print(mylist5)
output

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Dictionary:

  1. Empty dictionary

dict.clear()

dict1 = {‘key1’:1, ‘key2’:2}
dict1.clear()
print(dict1)
output

{}

  1. Designated delete

Use the pop method to specify to delete an item in the dictionary

dict1 = {‘key1’:1, ‘key2’:2}
d1 = dict1.pop(‘key1’)
print(d1)
print(dict1)
output

1
{‘key2’: 2}

  1. Iterating over the dictionary

dict2 = {‘key1’:1, ‘key2’:2}
mykey = [key for key in dict2]
print(mykey)
myvalue = [value for value in dict2.values()]
print(myvalue)
key_value = [(k, v) for k, v in dict2.items() ]
print(key_value)
output

[‘key1’, ‘key2’]
[1, 2]
[(‘key1’, 1), (‘key2’, 2)]
4. fromkeys

Used to create a new dictionary, with the elements in the sequence as the keys of the dictionary, and value is the initial value corresponding to all the keys of the dictionary

keys = ['zhangfei','guanyu','liubei','zhaoyun']
dict.fromkeys(keys, 0)
output

{'zhangfei': 0,'guanyu': 0,'liubei': 0,'zhaoyun': 0}

3. Briefly describe string encoding in Python

In the initial design of the computer, 8 bits were used as a byte. The largest integer that a byte can represent is 255 (binary 11111111 = decimal 255). If you want to represent a larger integer, you must use more bytes.
At the earliest, computers only had ASCII encoding, that is, they only contained uppercase and lowercase English letters, numbers, and some symbols. These were obviously not enough for other languages, such as Chinese and Japanese. Later, Unicode was invented. Unicode unified all languages ​​into a set of encodings, so that there would be no more garbled problems. When it needs to be saved to the hard disk or needs to be transferred, it is converted to UTF-8 encoding. UTF-8 is a variable-length encoding method belonging to Unicode.

In Python, a string encoded in Unicode can be encoded into specified bytes using the encode() method, or bytes can be encoded into a string using the decode() method.

4. Print the nine-nine-nine multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print("%s*%s = %s"%(i,j,i*j),end="; ")
    print()

5. The difference between __new__ and init in object-oriented

__new__ is called before the instance is created, because its task is to create an instance and return the instance object, which is a static method.
__init__ is called when the instance object is created, and then sets some initial values ​​of the object properties, usually used to initialize a class instance. Is an instance method.

1. __new__ must have at least one parameter cls, which represents the current class. This parameter is automatically recognized by the Python interpreter when it is instantiated.
2. __new__ must have a return value to return the instantiated instance. This point must be paid special attention to when implementing __new__ by yourself. You can return the parent class (via super(current class name, cls)) __new__ instance , Or directly an instance of __new__ of object.
3. __init__ has a parameter self, which is the instance returned by this __new__. __init__ can complete some other initialization actions on the basis of __new__, and __init__ does not require a return value.
4. If __new__ creates an instance of the current class, it will automatically call the __init__ function. The first parameter of the __new__ function called in the return statement is cls to ensure that it is an instance of the current class. If it is another class The name of the class; then the actual creation and return are instances of other classes, in fact, the __init__ function of the current class will not be called, nor will the __init__ function of other classes be called

6. Realize the dichotomy search function

Binary search requires that the objects must be in order, and its basic principles are as follows:

1. Starting from the middle element of the array, if the middle element happens to be the element to be searched, the search process ends;

2. If a particular element is larger or smaller than the middle element, search in the half of the array that is larger or smaller than the middle element, and start the comparison from the middle element just like the beginning.

3. If the array is empty at a certain step, it means it cannot be found.

# 二分法查找
# 从列表test = [1,5,8,16,24,48,59,80]
def erfen(list_number,n):
    begin = 0;
    end = len(list_number)-1;
    while begin <= end:
        mid = (begin + end)//2;
        if n > list_number[mid]:
            begin = mid + 1;
        else:
            if n < list_number[mid]:
                end = mid -1;
            else:
                print("第%s个数:"% (mid+1));
                break;

test = [1,5,8,16,24,48,59,80,90];
print("总数列为:",test);
a = int(input("请输入查找的数:"));
erfen(test,a);

7. String formatting method

  1. Use the% operator
print("This is for %s" % "Python")
print("This is for %s, and %s" %("Python", "You"))

output

This is for Python
This is for Python, and You
  1. str.format

In Python3, this new string formatting method was introduced.

print("This is my {}".format("chat"))
print("This is {name}, hope you can {do}".format(name="zhouluob", do="like"))

output

This is my chat
This is zhouluob, hope you can like
  1. f-strings

In Python3-6, this new string formatting method was introduced.

name = "luobodazahui"
print(f"hello {name}")

output

hello luobodazahui

#一个复杂些的例子:

def mytest(name, age):
    return f"hello {name}, you are {age} years old!"
people = mytest("luobo", 20)
print(people)
output

hello luobo, you are 20 years old!

8. Implement a simple API

Use flask to construct a web server

 from flask import Flask, request
 app = Flask(__name__)
 
 @app.route('/', methods=['POST'])
 def simple_api():
     result = request.get_json()
     return result
 
 
if __name__ == "__main__":
    app.run()

9. Realize a Fibonacci sequence

Fibonacci sequence: Also known as the golden section sequence, it refers to such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
In mathematics, the Fibonacci sequence is as follows It is defined in a recursive way: F(1)=1, F(2)=1, F(n)=F(n-1)+F(n-2) (n>=2, n∈N*)

a,b = 1,1
lst = [1]
n = int(input("请输入第n个数:"))
for i in range(n-1):
    lst.append(b)
    a,b = b,a+b #关键在这句

print("第%s个数为:%s"%(n,a))
print(lst)
def fpnq(n):
    i = 3;
    j = 1;
    b = 1;
    # a = 2;
    if n == 0:
        print("cuowu");
    elif n == 1:
        print("1");
    elif n == 2:
        print("1,1")
    else:
        while(i <= n):
            if i ==3:
                print("1,1",end=',')
            j,b = b,j+b;
            # a = j + b;
            # j = b;
            # b = a;
            print(b, end=',');
            i = i + 1;

fpnq(10);

10. Bubble sort

# 冒泡排序 arr = [9,7, 4, 3, 67, 34, 1, 8,42]

arr = [9,7, 4, 3, 67, 34, 1, 8,42];
print("排序前的数列:",arr);

def maopao(arr):
    n = len(arr);
    for i in range(0,n-1):
        for j in range(0,n-1-i):
            if arr[j] > arr[j+1]:
                arr[j],arr[j+1] = arr[j+1],arr[j];

maopao(arr);
print("排序后的数列:",arr);

11. Quick sort

The idea of ​​fast sorting: first select any data (usually the first number of the array) as the key data, and then put all numbers smaller than it before it, and all numbers larger than it after it. This process is called a quick sort, and then recursively sort the data on both sides.

Select benchmark value: pick out an element from the sequence, called "pivot";
segmentation: reorder the sequence, all elements smaller than the benchmark value are placed in front of the benchmark, and all elements larger than the benchmark value are placed in the benchmark Behind (the number equal to the reference value can go to either side). After the end of this segmentation, the sorting of the reference value has been completed;
recursively sort subsequences: recursively sort the subsequences of elements smaller than the reference value and the subsequences of elements greater than the reference value.

list1 = [9, 7, 4, 3, 67, 34, 1, 8, 42];
def partition(arr, low, high):
    i = (low - 1)  # 最小元素索引
    pivot = arr[high]

    for j in range(low, high):

        # 当前元素小于或等于 pivot
        if arr[j] <= pivot:
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]


    arr[i + 1], arr[high] = arr[high], arr[i + 1]

    return (i + 1)


def quicksort(arr, low, high):
    if low < high:
        pi = partition(arr, low, high)

        quicksort(arr, low, pi - 1)
        quicksort(arr, pi + 1, high)


quicksort(list1, 0, len(list1) - 1)

print(list1)

Arrangement of basic knowledge of
Python interview (Part 1) Arrangement of basic knowledge of Python interview (Part 2)

Guess you like

Origin blog.csdn.net/m0_37882192/article/details/115002061