Common job interview questions: Python full resolution of common interview questions with answers

Python is a very popular programming language, along with machine learning in recent years, the development of cloud computing and other technologies, Python jobs demand higher and higher. I collected 110 Python interviewer frequently asked questions for your reference study. Space issues, divided into two sub push next week will share with face questions next 55 ~

1, the sum of a line of code to achieve 1--100

Using the sum () function sum.

2, how to modify global variables inside a function

Modify global use global variables.

3, lists five python standard library

os: provides functions related to the operating system with a lot of

sys: command-line arguments commonly used

re: regular match

math: math

datetime: date and time of treatment

4, how to merge two dictionaries and dictionaries delete key

del and update methods.

5, under the python's GIL talk

GIL Global is the python interpreter lock, the same process if there are multiple threads running, a thread when running python program will occupy the python interpreter (ie had a lock GIL), the other threads within that process can not run, and so the thread running after other threads to run. If the process thread running encountered time-consuming operation, the interpreter unlock the lock, so that other threads to run. So in multiple threads, the thread is still running is a sequential, not simultaneous.

Run multiple processes at the same time in each process can be allocated as system resources, equivalent to each process has a python interpreter, it can achieve multi-process multiple processes, the big disadvantage is that the process of system resource overhead.

6, python list of methods to achieve weight

First go through a set of heavy, in turn list.

7, Fun (* args, * kwargs) in args, ** kwargs What does it mean?

Distinction 8, python2 python3 and a range (100) of

python2 return to the list, python3 returns an iterator, save memory.

9, in a word to explain what kind of language can be used decorator?

As a function of transmission parameters of the language, you can decorator.

10, python built-in data types which

Integer --int

Boolean --bool

String --str

--List list

Tuple --tuple

Dictionary --dict

11, the object-oriented brief new and init difference

init is the initialization method, after creating an object, it was immediately called by default, and can receive parameters, as

(. 1) new new have at least one parameter CLS, representatives of this class, this parameter is automatically recognized by the Python interpreter at instantiation.

(2) new must have a return value, out of the instantiated instances returned, this is achieved in their new Particular care may return parent class (by super (current class name, CLS)) new instance out of, or directly It is the object of the new instance out.

(. 3) the init has a parameter self, is this new instances returned, the init in the new complete other initialization operation based on, the init no return value.

(4) If the new creation is an instance of the current class will automatically call the init function, the return statement which called new first parameter of the function is to ensure that the current cls class instance, if other class class name; then the actual creation of the return is another instance of the class, in fact, it does not call the current class init function, it does not call other classes init function.

12, briefly with ways to open the file to help me deal with what we do?

Open the file during read and write when there may be some abnormal condition, according to conventional f.open.

Written, we need to try, except, finally, do the abnormality judgment, and the final document no matter what the situation, we must execute finally f.close () closes the file, with ways to help us achieve finally in f.close.

(Of course, there are other custom features, are interested can study method with source code)

13, the list [1,2,3,4,5], using the map () function output [1,4,9,16,25], and the formula used to derive a list number greater than 10 is extracted, the final output [16 , 25]

The first parameter map () function is a fun, the second parameter is typically List, the third parameter List can be written, can not write, according to the needs.

14, python random integer generated randomly decimal, fractional method between 0--1

Random integer: integer within generating section random.randint (a, b).

Random decimal: accustomed numpy library using np.random.randn (5) generates a random decimal 5.

0-1 random decimal: random.random (), parameter passing in the bracket.

15, to avoid the escape string plus what letter represents the original string?

r, expressed the need for the original string, does not escape special characters.

16, <div class = "nam"> China </ div>, with regular label matched the contents inside ( "China"), wherein the class name of the class is undefined

17, python asserted way of example

assert () method, the assertion is successful, the program continues, the assertion fails, the program error.

18, student data table has id, name, score, city field, where name is the name may have repeated the need to eliminate duplicate rows, please write sql statement

select distinct name from student

19,10 a Linux common commands

ls pwd cd touch rm mkdir tree cp mv cat more grep echo

20, python2 and python3 difference? Listed five

(1) Python3 must be printed using the print content wrapped in parentheses, such as print ( 'hi');

Python2 embodiment may be used with parentheses, a space may be used to separate print content, such as print 'hi';

(2) python2 range (1,10) returns a list, to python3 returned iterator save memory;

(3) python2 used ascii encoding, python using utf-8 encoded;

(4) python2 unicode string representing the sequence, str represents a sequence of bytes; str string representing the sequence to python3, byte represents the byte sequence;

(5) python2 Chinese normal display for introducing coding statement, is not required to python3;

(6) python2 is the raw_input () function, python3 is input () function.

21, the variable data types are listed in python and immutable data type, and briefly the principle

Immutable data types: numeric, string, string and tuple tuple;

The method does not allow the value of the variable is changed, if the change of the value of the variable, corresponding to an object is built, and the value for the same object in memory only one object (an address), as shown by id () can id to print the object.

Variable data types: lists list and dictionary dict;

Allowed value of the variable is changed, i.e. if the variable append, + = like this operation, just change the value of the variable, rather than create a new object, the object referenced by the variable address does not change, but the same values ​​of different objects, the different objects in memory will exist, i.e., each object has its own address, memory for the object corresponding to the same values ​​stored in more than one, where the reference count is not present, is real Object.

22, s = "ajldjlajfdljfddd", to weight and small to large outputs "adfjl"

to set weight, to turn into List weight, by a sorting sort method, reeverse = False is from small to large;

list is the same data type, s.sort when no return value, so commented code written is incorrect.

23, achieved by multiplying the number of two lambda functions

24, according to the dictionary from small to large bond

dict={"name":"zs","age":18,"city":"深圳","tel":"1362626627"}

25, the number of library collections using the statistical method of Counter string for each word appears "kjalfj; ldsjafl; hdsllfdhg; lahfbl; hl; ahlf; h"

26, the string a = "not 404 found Zhang Shenzhen 99", each word is a space intermediate, with a regular alphanumeric filtered off, the final output "San Shenzhen"

Incidentally paste matching decimal code, although able to match, but the robustness needs further confirmation.

27, filter methods to obtain a list of all of the odd and the new list structure, a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

filter () function is used to filter sequences, filtered ineligible element returns a list of qualified new elements. The receiving two parameters, as a function of a first, a second sequence, each element of the sequence as an argument to a function arbitrates, then return True or False, and finally returns True elements into a new list.

28, a list of all the odd list of requirements to derive the formula and the new list structure, a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

29, regular re.complie role

re.compile regular expression is compiled into an object, speed, and reused.

30, a = (1,) b = (1), c = ( "1") are what type of data?

31, two lists [1,5,7,9] and [2,2,6,8] merger [1,2,2,3,6,7,8,9]

may be added individually extend another set to the list of elements, different from the overall append added.

32, delete files, and delete files in python linux command method

python: os.remove (filename)

linux: rm filename

33, log log, we need to record the error, warning such occurrence time with a time stamp, print the current time stamp "2018-04-01 11:38:54" with datetime module

The way the code is also labeled week.

34, a database query optimization methods

Foreign keys, indexes, union query, select specific fields, and so on.

35. Please list any chart you will (bar, line, etc.) drawn open source libraries, third party also OK

pychart、matplotlib。

36, write a custom exception code

Custom exception thrown with a raise.

37, regular expression matching, (. ) And (. ?) To match the difference?

(*) Are greedy match, will meet regular back as many matches,

(. *?) Non-greedy match, will meet the regular fewer matches as possible.

38, a brief Django orm

ORM, spelling Object-Relation Mapping, meaning the object - relational mapping.

To achieve a decoupling of the data model and database by simple configuration database can easily be replaced without the need to modify the code only needs to object-oriented programming, database engine based on docking, translated into the corresponding sql statement orm operating on essentially all use Django development projects without concern for the underlying program using MySQL, Oracle, sqlite ...., if the database migration, you only need to replace the Django database engine can be.

39, [[1,2], [3,4], [5,6]] line of code to expand the list, drawn [1,2,3,4,5,6]

Sao operation list comprehension

Run procedure: for i in a, each i is [1,2], [3,4], [5,6], for j in i, j is each 1,2,3,4,5,6 after the merger is the result.

There are more Sao method, will turn into a list of numpy matrix numpy by the flatten () method, the code will always be only more show, most did not show ~

40, x = "abc", y = "def", z = [ "d", "e", "f"], were determined x.join (y) and x.join (z) results returned

join () brackets is iterable, x iterative intermediate object may be inserted, the string formed, consistent results, there is no sudden feeling common string operations will not play ~

Incidentally suggest that you learn at os.path.join () method, the path of joining frequently used, also used the join, and string operations join any difference, the problem we can access relevant documents, the latter have the answer.

41, an example of abnormal correlation module try except else finally the

try..except..else not caught exceptions, the else statement;

try..except..finally whether Exception caught, finally statement is executed.

42, python exchange two values

43, illustrated zip () function usage

zip () function when the operation will be as a parameter to one or more sequences (iterables), returns a list of tuples. These sequences simultaneously in side by side pairs of elements.

zip () parameter can take any type of sequence, but can also have more than two parameters; when the length parameter is not passed at the same time, zip automatically shortest sequence length is subject to interception, the tuple is obtained.

44, a = "Zhang points 98", with the re.sub, 98 will be replaced by 100

45, write five common sql statement

show databases;

show tables;

desc table name;

select * from 表名;

delete from 表名 where id=5;

update students set gender=0,hometown="北京" where id=5

46, a = "hello" and b = "Hello" type encoded into bytes

47, [1,2,3] + [4,5,6] is the result of how much?

Two lists are added, equivalent to extend.

48, to improve the operating efficiency of the method python

(1) using the generator, because it is possible to save a lot of memory

(2) cyclic code optimization, to avoid excessive repetition code execution

(3) the core module Cython PyPy the like, to improve efficiency

(4) multi-process, multi-thread, coroutine

(5) if elif plurality of determination conditions, the conditions can be most likely to occur to the front write, thus reducing the number of times the program determines, efficiency

49, briefly, and redis difference mysql

redis: non-memory relational database, data is stored in memory and speed.

mysql: a relational database, data is stored on disk, retrieve, then there will be some Io operations, access speed is relatively slow.

50, how to handle encounters bug

(1) details of error, () Print Print, can be performed to a print () described above code generally no problem, if the detection program segment in question, if it can alert or js console.log

(2) if it involves a number of third-party frameworks, go check the official documentation or technical blog.

(3) For management and classified summary of the bug, the general test will test out the bug with teambin bug management tools such as record, then we will make changes one by one, the process is modified to improve their understanding of the business logic and programming logic rigor way, I will make some notes record collection.

(4) lead packet problems, urban positioning error caused by more than one pronunciation.

51, regular, the matching date 2018-03-20

url='https://sycm.taobao.com/bda/tradinganaly/overview/get_summary.json?dateRange=2018-03-20%7C2018-03-20&dateType=recent1&device=1&token=ff25b109b&_=1521595613462'

There are students asked to be regular, in fact match is not difficult to extract some features statements by (. *?) To match.

52, list = [2,3,5,4,9,6], from small to large, not allowed to use Sort, output [2,3,4,5,6,9]

Use min () method to find a minimum of the original list to delete the minimum value, the minimum value addition of the new list, the recursive call to get the minimum function, repeatedly.

53, write a single column mode

Because the object is created new method of execution, and must return to return to instantiate out of the object cls .__ instance exists and does not exist to create an object, it exists to return the object to ensure that only one instance of existence (single) object print ID, the same values, the same description of the object.

54, two decimal places

Title itself is only a = "%. 03f"% 1.3335, so that the results of a calculation, in order to retain the decimal expansion of ideas, provide round method (value, number of bits reserved).

55, seeking three methods to print results

fn ( "one", 1) to pass directly to the key-value dictionary;

After fn ( "two", 2) because the dictionary is the type of variable data in memory, so point to the same address, the new amount of parameters passed, will increase equivalent to the key-value pair dictionary;

fn ( "three", 3, {}) as a new dictionary passed, it is no longer the original default parameters of the dictionary.

Guess you like

Origin blog.51cto.com/14529670/2439746
Recommended