Starting today, I will share some interview questions related to Python with you.

All Python bosses please go around!! Of course, if you can give some Pointers, that would be great!

Basic Part 1

1. Why learn Python

Python is a language that is easy to understand, easy to learn, and increasingly popular with the AI trend.

2. Differences between interpreted and compiled languages

Compiled language: the complete compilation of the source program into binary executable program. You can then run the program directly. Such as C, C++

Interpreted language: the source code to translate a sentence, and then execute a sentence, until the end! Java programs also need to be compiled, but instead of being compiled directly as machine language, they are compiled as bytecodes and then interpreted to execute bytecodes.

3. Briefly describe strings, lists, tuples, and dictionaries in Python

String (STR) : STRINGS are arbitrary text enclosed in quotes and are the most commonly used data type in programming languages.

List: A list is an ordered collection to which elements can be added or removed.

Tuple: Tuples are also ordered collections, but cannot be modified. Tuples are immutable.

Dict: Dictionaries are unordered collections of key-values.

Set: A set of keys. Each element is unique, non-repetitive, and unordered.

4. Briefly describe the common methods of the above data types

string

  1. slice
mystr='luobodazahui'
mystr[1:3]
Copy the code

output

'uo'
Copy the code
  1. format
mystr2 = "welcome to luobodazahui, dear {name}"
mystr2.format(name="baby")
Copy the code

output

'welcome to luobodazahui, dear baby'
Copy the code
  1. join

Can be used to concatenate strings, concatenate strings, tuples, and elements in a list with the specified character (delimiter) to generate a new string.

mylist = ['luo'.'bo'.'da'.'za'.'hui']
mystr3 = The '-'.join(mylist)
print(mystr3)
Copy the code

outout

'luo-bo-da-za-hui'
Copy the code
  1. replace

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

mystr4 = 'luobodazahui-haha'
print(mystr4.replace('haha'.'good'))
Copy the code

output

luobodazahui-good
Copy the code
  1. split

Cut through the string to get a list.

mystr5 = 'luobo,dazahui good'
# Split by space
print(mystr5.split())
# divided by h
print(mystr5.split('h'))
# separate by comma
print(mystr5.split(', '))
Copy the code

output

['luobo,dazahui'.'good']
['luobo,daza'.'ui good']
['luobo'.'dazahui good']
Copy the code

The list of

  1. slice

With the string

  1. Append and extend

Add the element to the list for China

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

outout

[1, 2, 3, 4] [1, 2, 3, 4]Copy the code
  1. Remove elements

Del: Deletes the file based on the subscript

Pop: Remove the last element

Remove: Deletes an element based on its value

mylist4 = ['a'.'b'.'c'.'d']
del mylist4[0]
print(mylist4)
mylist4.pop()
print(mylist4)
mylist4.remove('c')
print(mylist4)
Copy the code

output

['b'.'c'.'d']
['b'.'c']
['b']
Copy the code
  1. Element ordering

Sort: rearranges the list in a specific order. The default is from small to large. Reverse =True can be changed to reverse from large to small.

Reverse: Inverts the list.

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

output

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Copy the code

The dictionary

  1. Empty dictionary

dict.clear()

dict1 = {'key1': 1,'key2':2}
dict1.clear()
print(dict1)
Copy the code

output

{}
Copy the code
  1. Specify the delete

Use the POP method to specify that an item in the dictionary should be deleted

dict1 = {'key1': 1,'key2':2}
d1 = dict1.pop('key1')
print(d1)
print(dict1)
Copy the code

output

1
{'key2'2} :Copy the code
  1. Through 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)
Copy the code

output

['key1'.'key2'[(] [1, 2]'key1', 1), ('key2', 2)]
Copy the code
  1. fromkeys

Use to create a new dictionary with the elements in the sequence as the dictionary keys and value as the initial values of all the keys in the dictionary

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

output

{'zhangfei': 0.'guanyu': 0.'liubei': 0.'zhaoyun': 0}
Copy the code

5. Describe string encoding in Python

The computer was originally designed with eight bits as one byte. The largest integer represented by a word saving is 255 (binary 11111111= decimal 255). If you want to represent larger integers, you must use more bytes. At first, computers had only ASCII code, which contained only upper and lower case English letters, numbers, and symbols, which were obviously inadequate for other languages such as Chinese and Japanese. Then came Unicode, which unified all languages into one code so that there was no more garbled code. When it needs to be saved to hard disk or transferred, it converts to UTF-8 encoding. Utf-8 is a Unicode variable-length encoding. In Python, Unicode encoded strings can be encoded into specified bytes using the encode() method, or bytes into strings using the decode() method.

encode

"Chinese".encode('utf-8')
Copy the code

output

b'\xe4\xb8\xad\xe6\x96\x87'
Copy the code

decode

b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
Copy the code

output

'Chinese'
Copy the code

6. One line of code to exchange values

a = 1
b = 2
a, b = b, a
print(a, b)
Copy the code

output

2 1
Copy the code

7. The difference between is and ==

Let’s start with an example

c = d = [1.2]
e = [1.2]
print(c is d)
print(c == d)
print(c is e)
print(c == e)
Copy the code

output

True
True
False
True
Copy the code

== is the comparison operator, which only checks whether the value of objects is consistent, while IS checks whether the identity (memory address) of objects is consistent. The identity of the object can be seen through the id() method.

id(c)
id(d)
id(e)
Copy the code

output

188748080
288748080
388558288
Copy the code

As you can see, the is comparison returns True only if the IDS are consistent, and the == comparison returns True if the values are consistent

8. Argument types in Python functions

Positional arguments, default arguments, variable arguments, keyword arguments

9. * ARG and ** KWARg function

Allows us to pass in multiple arguments when calling a function

def test(*arg, **kwarg):
    if arg:
        print("arg:", arg)
    if kwarg:
        print("kearg:", kwarg)
test('ni'.'hao', key='world')
Copy the code

output

arg: ('ni'.'hao')
kearg: {'key': 'world'}
Copy the code

As you can see, *arg converts positional arguments to tuple **kwarg converts keyword arguments to dict

10. One line of code for the sum of 1-100

sum(range(1, 101))
Copy the code

11. Obtain the current time

import time
import datetime
print(datetime.datetime.now())
print(time.strftime('%Y-%m-%d %H:%M:%S'))
Copy the code

output

The 12019-06-07 18:12:11. 165330 22019-06-07 18:12:11Copy the code

12. PEP8 specification

Here are 10 simple examples:

  • Try to avoid confusing letters such as lowercase ‘L’, uppercase ‘O’, and uppercase ‘I’.

  • Function names are all lowercase and can be underlined.

  • Constants are named in all caps and can be underlined.

  • Name Boolean elements with a has or IS prefix, as in is_connect = True; has_member = False

  • Do not add a semicolon to the end of a line, nor do you use a semicolon to place two commands on the same line.

  • Do not connect lines with backslashes.

  • There is 2 empty lines between top-level definitions, 1 empty line between method definitions, and 2 empty lines between top-level definitions.

  • If a class does not inherit from another class, it explicitly inherits from Object.

  • A class, method, or variable that is used internally must be prefixed with ‘_’ to indicate that it is used internally.

  • Assertions are used to implement static type detection.

13. Deep and shallow copies of Python

Shallow copy

import copy
list1 = [1, 2, 3, [1, 2]]
list2 = copy.copy(list1)
list2.append('a')
list2[3].append('a')
print(list1, list2)
Copy the code

output

[1, 2, 3, [1, 2, 'a'[1, 2, 3, [1, 2,'a'].'a']
Copy the code

As you can see, the shallow copy only successfully “independently” copies the outer layer of the list, while the inner list of the list is still shared

Deep copy

import copy
list1 = [1, 2, 3, [1, 2]]
list3 = copy.deepcopy(list1)
list3.append('a')
list3[3].append('a')
print(list1, list3)
Copy the code

output

[1, 2, 3, [1, 2]] [1, 2, 3,'a'].'a']
Copy the code

Deep copy allows the two lists to be completely separate, so that operations on each list do not affect the other.

14. View the output of the code below

def num(a):
    return [lambda x:i*x for i in range(4)]
print([m(1) for m in num()])
Copy the code

output

[3, 3, 3, 3]
Copy the code

And when you run it, you can see that I is 3, which is amazing

Mutable versus immutable types

Mutable data types: list, dict, set

Immutable data types: int/float, STR, tuple

16. Print the 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(a)Copy the code

output

11*1=1 22*1=2 2*2=4 33*1=3 3*2=6 3*3=9 44*1=4 4*2=8 4*3=12 4*4=16 55*1=5 5*2=10 5*3=15 5*4=20 5*5=25 66*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 77*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6= 49 88*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 99*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81Copy the code

The print function, by default, wraps lines, and has a default argument end. If we set end to “” as in the example, then the print function will not wrap lines, and we will have the effect of multiplying The Times table.

17. Functions of Filter, Map, and Reduce

The filter function is used to filter sequences. It takes a function and a sequence, applies the function to each element of the sequence, and then decides whether to keep or discard the element based on whether the return value is True or False.

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list(filter(lambda x: x%2 == 1, mylist))
Copy the code

output

[1, 3, 5, 7, 9]
Copy the code

Keep odd list

The map function takes a function and a sequence and applies the function to each element of the sequence, returning an iterable

mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list(map(lambda x: x*2, mylist))
Copy the code

output

[2, 4, 6, 8, 10, 12, 14, 16, 18]
Copy the code

The reduce function is used for recursive calculation, which also requires passing in a function and a sequence, and computing the result of the function and sequence elements with the next element.

from functools import reduce
reduce(lambda x, y: x+y, range(101))
Copy the code

output

15050
Copy the code

As you can see, the above three functions can be used in combination with anonymous functions to write powerful and concise code.

18. Re match and search

The match() function only checks if the character to be matched is at the beginning of the string. Search () scans the entire string for a match

19. The difference between __new__ and __init__ in object orientation

__new__ is called before the instance is created, because its job is to create the instance and then return the instance object, which is a static method.

__init__ is called when the instance object has been created and then sets some initial values for the object properties, usually when initializing a class instance. Is an instance method.

1. __new__ must have at least one argument, CLS, representing the current class, which is automatically recognized by the Python interpreter at instantiation time.

2, __new__ must have a return value, return the instantiated instance, this is particularly important when implementing __new__, can return the parent (super(current class name, CLS)) __new__ instance, Or an instance of object’s __new__ directly.

3. __init__ takes an argument, self, which is an instance of __new__. __init__ can do some other initialization on __new__, and __init__ does not return a value.

4. If __new__ creates an instance of the current class, the __init__ function is automatically called. CLS is the first argument to the __new__ function in the return statement to ensure that it is the current class instance. The __init__ function of the current class is not called, and the __init__ function of the other class is not called.

20. Triadic operation rules

a, b = 1, 2
If a>b is true, print a-b; otherwise, print a+b
h = a-b if a>b else a+b
Copy the code

output

13
Copy the code

21. Generate random numbers

print(random.random())
print(random.randint(1, 100))
print(random uniform (1, 5))Copy the code

output

10.03765019937131564
218
31.8458555362279228
Copy the code

22. Zip function usage

The zip() function takes an iterable object as an argument, packs the corresponding elements of the object into tuples, and returns a list of those tuples

list1 = ['zhangfei'.'guanyu'.'liubei'.'zhaoyun']
list2 = [0, 3, 2, 4]
list(zip(list1, list2))
Copy the code

output

[('zhangfei', 0), ('guanyu'And 3), ('liubei', 2), ('zhaoyun'And 4)]Copy the code

23. Difference between Range and Xrange

Range ([start,] stop[, step]), generates a sequence based on the range specified by start and stop and the step size set by step. Xrange generates a generator, which can save a lot of memory.

24. The with method opens the function of the file

Open files may have some exceptions when they are read or written. If f.pen is written normally, we need to try,except,finally to check for exceptions, and finally f.close() to close the file no matter what happens. The with method helps us implement F.close in finally.

25. What is a greedy match for a re

Greedy matching is the default in Python.

Greedy pattern: Regular expressions generally tend to match with maximum length.

Non-greedy mode: As few matches as possible as long as the entire expression matches successfully.

26. Why not pass in mutable objects as default arguments to functions

Such as:

def test(L=[]):
    L.append('test')
    print(L)
Copy the code

output

test(a)# ['test']
test(a)# ['test', 'test']
Copy the code

The default argument is a list of mutable objects []. When Python defines a function, the default argument L is calculated to be []. Each time a function is called, if the value of L changes, the next time it is called, the default argument will no longer be the value of [].

27. String rotation list

mystr = '1, 2, 3'
mystr.split(', ')
Copy the code

output

['1'.'2'.'3']
Copy the code

28. Convert the string to an integer

mylist = ['1'.'2'.'3']
list(map(lambda x: int(x), mylist))
Copy the code

output

[1, 2, 3]
Copy the code

29. Delete duplicate values from the list

mylist = [1, 2, 3, 4, 5, 5]
list(set(mylist))
Copy the code

30. String word statistics

from collections import Counter
mystr = 'sdfsfsfsdfsd,were,hrhrgege.sdfwe! sfsdfs'
Counter(mystr)
Copy the code

output

 Counter({'s': 9,
          'd': 5,
          'f': 7,
          ', ': 2.'w': 2.'e': 5,
          'r': 3.'h': 2.'g': 2.'. ': 1,
         '! ': 1})
Copy the code

31. List derivation, find odd and even numbers

[x for x in range(10) if x%2 == 1]
Copy the code

output

[1, 3, 5, 7, 9]
Copy the code

32. One line of code expands the list

List1 = [[1, 2], [3, 4], [5, 6]] [jfor i in list1 for j in i]
Copy the code

output

[1, 2, 3, 4, 5, 6]
Copy the code

33. Implement dichotomy search function

Binary search algorithm is also known as semicircle search, the basic idea is semicircle, compare the size and then semicircle search, must be an ordered sequence can use the binary search. A recursive algorithm

 def binary_search(data, item):
     # recursive
     n = len(data)
     if n > 0:
         mid = n // 2
         if data[mid] == item:
             return True
         elif data[mid] > item:
             return binary_search(data[:mid], item)
        else:
            return binary_search(data[mid+1:], item)
    returnFalse list1 =,4,5,66,78,99,100,101,233,250,444,890 [1] binary_search (list1, 999).Copy the code

Non-recursive algorithms

 def binary_search(data, item):
     # non-recursive
     n = len(data)
     first = 0
     last = n - 1
     while first <= last:
         mid = (first + last)//2
         if data[mid] == item:
             return True
        elif data[mid] > item:
            last = mid - 1
        else:
            first = mid + 1
    returnFalse list1 =,4,5,66,78,99,100,101,233,250,444,890 [1] binary_search (list1, 99).Copy the code

34. Dictionary and JSON conversion

Turn a json dictionary

import json
dict1 = {'zhangfei': 1,"liubei": 2."guanyu": 4."zhaoyun":3}
myjson = json.dumps(dict1)
myjson
Copy the code

output

'{"zhangfei": 1, "liubei": 2, "guanyu": 4, "zhaoyun": 3}'
Copy the code

Turn a json dictionary

mydict = json.loads(myjson)
mydict
Copy the code

output

{'zhangfei': 1, 'liubei': 2.'guanyu': 4.'zhaoyun': 3}
Copy the code

35. List derivations, dictionary derivations, and generators

import random
td_list=[i for i in range(10)]
print("List derivation", td_list, type(td_list))
ge_list = (i for i in range(10))
print("Generator", ge_list)
dic = {k:random.randint(4, 9)for k in ["a"."b"."c"."d"]}
print("Dictionary derivation",dic,type(dic))
Copy the code

output

Table derivation [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class'list'> Generator <generator object <genexpr> at 0x0139F070>'a': 6, 'b': 5, 'c': 8, 'd': 9} <class 'dict'>
Copy the code

36. Describe the differences between read, readline and readlines

Read Reads the entire file

Readline reads the next line, using the generator method

Readlines reads the entire file into an iterator for us to traverse

37. Mess up a list

list2 = [1, 2, 3, 4, 5, 6]
random.shuffle(list2)
print(list2)
Copy the code

output

[4, 6, 5, 1, 2, 3]
Copy the code

38. Reverse the string

str1 = 'luobodazahui'
str1[::-1]
Copy the code

output

'iuhazadoboul'
Copy the code

39. Functions of single and double underscores

__foo__ : A convention, an internal Python name, used to distinguish other user-defined names from collisions, such as __init__() and __del__() and __call__() special methods.

_foo: a convention to specify that a variable is private. Cannot be imported with from Module import *, otherwise accessed as public variables.

__foo: This has real meaning: the parser replaces this name with _classname__foo to distinguish it from other classes that have the same name. It cannot be accessed directly as a public member, but by means of object name. _classname __xxx.

40. New and old classes

A. In Python, any classes that inherit from Object are new classes

B. Python3 has only new classes

C. Python2 contains new classes that inherit from object, and classical classes that do not write superclasses

D. Classical classes are currently barely used in Python

41. What are the characteristics of inheritance in Python object-oriented

A. Support both single inheritance and multiple inheritance. Single inheritance is supported when only one parent class exists, and multiple inheritance is supported when multiple parent classes exist.

B. A subclass inherits all attributes and methods of the parent class. A subclass can also override variables and methods of the parent class with the same name.

C. The base class construction (__init__()) method in inheritance is not called automatically; it needs to be called specifically in the construction of its derived class.

D. When calling a method of the base class, prefix the base class name with the self parameter variable. You don’t need to take the self argument when you call a normal function from a class.

42. The super function

The super() function is a method used to call the parent (superclass).

 class A():
     def funcA(self):
         print("this is func A")
 class B(A):
     def funcA_in_B(self):
         super(B, self).funcA()
 
     def funcC(self):
         print("this is func C")

ins = B()
ins.funcA_in_B()
ins.funcC()
Copy the code

output

this is func A
this is func C
Copy the code

43. Various functions in a class

It is mainly divided into instance method, class method and static method

Instance methods:

Definition: The first argument must be an instance object, usually named “self”, through which to pass instance properties and methods (or class properties and methods);

Call: Can only be called by instance objects.

Methods:

Definition: Use the decorator @classMethod. The first parameter must be the object of the current class, whose name is conventionally “CLS”, through which to pass attributes and methods of the class (not instance attributes and methods);

Call: Both instance objects and class objects can be called.

Static method:

Definition: Use the decorator @staticMethod. The arguments are optional. There are no “self” and “CLS” arguments, but no properties or methods of the class or instance can be used in the method body.

Call: Both instance objects and class objects can be called.

Static methods are functions in a class that do not require an instance. Static methods are primarily used to store logical code that belongs to a class but does not interact with the class itself. That is, in static methods, operations on methods and properties in the class are not involved. You can think of storing static methods in the namespace of this class. Class methods are methods that operate on the class itself as an object. The difference between this method and a static method is that it passes the class with the first argument, whether it is called from an instance or from a class.

44. How to determine whether it is a function or a method

Functions that are not bound to classes and instances are functions and functions that are bound to classes and instances are methods

Ordinary functions:

def func1():
    pass
print(func1)
Copy the code

output

<function func1 at 0x01379348>
Copy the code

Class functions:

 class People(object):
     def func2(self):
         pass
     @staticmethod
     def func3():
         pass
     @classmethod
     def func4(cls):
         pass
people = People()
print(people.func2)
print(people.func3)
print(people.func4)
Copy the code

output

<bound method People.func2 of <__main__.People object at 0x013B8C90>>
<function People.func3 at 0x01379390>
<bound method People.func4 of <class '__main__.People'>>
Copy the code

45. Isinstance and how it differs from type()

The isinstance() function checks whether an object is of a known type, similar to type().

The difference between:

Type () does not consider a subclass to be a parent type, regardless of inheritance.

Isinstance () considers a subclass to be a superclass type, considering inheritance.

 class A(object):
     pass
 class B(A):
     pass
 a = A()
 b = B()
 print(isinstance(a, A))
 print(isinstance(b, A))
 print(type(a) == A)
 print(type(b) == A)
Copy the code

output

True
True
True
False
Copy the code

46. Singleton versus factory pattern

Singleton pattern: The main purpose is to ensure that only one instance of a class exists.

Factory pattern: Includes a superclass that provides an abstract interface to create objects of a particular type, rather than deciding which objects can be created.

47. View all files in the directory

import os
print(os.listdir('. '))
Copy the code

48. Count a non-repeating three-digit number from 1 to 5

 A non-repeating three-digit number from # 1 to 5
 k = 0
 for i in range(1, 6):
     for j in range(1, 6):
         for z in range(1, 6):
             if(i ! = j) and (i ! = z) and (j ! = z): k += 1if k%6:
                     print("%s%s%s" %(i, j, z), end="|")
                else:
                    print("%s%s%s" %(i, j, z))
Copy the code

output

1123 | 124 | 125 | | 132 | 134 | 135 2142 143 152 154 3213 | | 153 | | 145 | 214 | | 231 | 215 234 235 4241 | 243 | | 245 | 251 | 253 | 254 5312 | 314 | 315 | | 321 | 324 | 325 6341 342 351 354 7412 | | 352 | | 345 | 413 | | 421 | 415 423 425 8431 | 432 | | 435 | 451 | 452 | 453 9512 | 513 | | 514 | 521 523 524 10531 | 532 | | 534 | 541 | 542 | 543Copy the code

49. Remove Spaces at the beginning and end of strings

str1 = " hello nihao "
str1.strip()
Copy the code

output

'hello nihao'
Copy the code

50. Remove Spaces between strings

str2 = "hello you are good"
print(str2.replace("".""))
"".join(str2.split(""))
Copy the code

output

helloyouaregood
'helloyouaregood'
Copy the code

That’s the end of part one of our interview questions series, and we’ll see you next time!

Welcome to follow my wechat public account – Radish Mixed Soup, or scan the qr code below, we can communicate, learn and progress together!