[Python] to what extent does Python learn to interview for a job (answer 1)

Yngz_ Miao 2020-11-13 07:51:37
python extent python learn interview

Go to Zhihu , See the post Python Learn how much you can interview for a job ?, stay Peach Blossom Island owner In his reply, he said 2019 The latest Python Interview questions , As well as Xudong The big guy has done most of the answers .

In a few posts, the blogger will , Combined with the big guy's answer , Answer these questions in more detail .

Source code of this article github Address https://github.com/yngzMiao/yngzmiao-blogs/tree/master/2020Q1/20200103.

Basic knowledge of

  1. List 5 Common use Python Standard library ?
import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing
  1. Python What are the built-in data types of ?
intfloatcomplex # Numerical type 
bool # Boolean type 
str # character string 
list # list 
tuple # Tuples 
dict # Dictionaries 
  1. sketch with Method to open the processing file to help me what we did ?
  • with The statement applies to Access to resources , Ensure that necessary cleanup operations are performed regardless of whether an exception occurs during use , Release resources , For example, the file is automatically closed after use 、 Automatic acquisition and release of locks in threads ;
  • with The sentence is Context manager , It is used to represent the environment before and after code execution . Context manager : contain __enter__ and __exit__ The object of the method is the context manager .
  • enter(): In execution with The statement before , First execute the method , Usually returns an instance object , If with Statements are as The goal is , Then assign the object to as The goal is .
  • exit(): In execution with After statement end , Automatically call __exit__() Method , Users release resources , if This method returns the Boolean value True, The program ignores exceptions .
  • Usage environment : File read and write 、 Automatic release of thread lock, etc .
with context_expression [as target(s)]:

here context_expression want Returns a context manager object , This object is not assigned to as In Clause target(s), It's the context manager __enter__() The return value of the method is assigned to the target(s).

Not very clear can refer to the link : In depth understanding of Python Context manager in .

  1. Python Variable and immutable data types ?
  • Immutable data types : After the data is created , The value of the data will no longer change , There are values 、 character 、 Yuanzu type ;
  • Variable data type : Don't create data after , The value of the data can change , There are lists 、 Dictionaries 、 Collection types .
  1. Python Get current date ?
# -*- coding: UTF-8 -*-
import datetime
import time
if __name__ == "__main__":
print(time.time()) # Time stamp 
print(time.strftime("%Y-%m-%d %H:%M:%S %w", time.localtime())) # Mm / DD / yyyy HHM / S 
print(datetime.datetime.now()) # Mm / DD / yyyy HHM / S 
  1. Count the number of occurrences of each word in the string .
def word_amount(sentence):
split_list = sentence.split()
dict_result = {
for word_name in split_list:
if word_name not in dict_result.keys():
dict_result[word_name] = 1
dict_result[word_name] += 1
return dict_result
if __name__ == '__main__':
sentence = "I can because i think i can"
dict_result = word_amount(sentence)

perhaps :

if __name__ == '__main__':
sentence = "I can because i think i can"
result = {
word: sentence.split().count(word) for word in set(sentence.split())}

perhaps :

from collections import Counter
if __name__ == '__main__':
sentence = "I can because i think i can"
counts = Counter(sentence.split())
  1. use python Delete files and use linux Command delete file method .
import os
rm demo.txt
  1. Write a custom exception code ?
class printException(Exception):
def testRaise():
raise printException('printErr')
if __name__ == '__main__':
except printException, e:
print e
  1. For example, in the exception module try except else finally The relevance of .
# -*- coding: UTF-8 -*-
def read_filedata(file_name):
file_obj = ""
# Exception code fragment to detect 
file_obj = open(file_name, "r")
result_data = file_obj.read()
except IOError, e:
# happen “IOError” Code snippet for exception handling 
file_obj = " file does not exist :"+ str(e)
# Did not trigger “IOError” Code snippet for exception execution , Return the data read 
return result_data
# Code snippets that execute with or without an error ,isinstance() Used to determine a data type 
if isinstance(file_obj, str):
return file_obj
elif isinstance(file_obj, file):
return " Unknown error , Please check your code ..."
if __name__ == '__main__':
result = read_filedata("abc.txt")
  1. encounter bug How to deal with it ?
  • First check the error message , Find the corresponding code according to the error information , General data structure or algorithm errors can be solved as long as the error code is found ;
  • Don't panic if you encounter a mistake that can't be solved for the time being , We can use the compiler's Debug Mode or add breakpoints in the code to check the code ;
  • If it still can't be solved bug, We can copy the error message , Search in search engines . No one can't write code bug, If you're in one bug It takes more than half an hour , Discuss with other colleagues ( Pay attention to moderation , It may cost some colleagues );
  • To open or find a new path or snap course : There are more ways than difficulties , In rapid development , We should give priority to the realization of functions rather than the operation efficiency , So there are some problems that can't be solved BUG You can think of another way to do it .

Linguistic characteristics

  1. Talk about right Python The difference between our understanding and other languages ?

Python It's a simple and beautiful grammar , It's powerful , It has a wide range of applications , A gate with a powerful and complete third-party library Strong type Of dynamic , portable , Scalable , Embeddable interpreted programing language .

Strong type language 、 The difference between weakly typed languages :

  • If the language often implicitly converts the type of variable , Then the language is Weak type language , If it's rarely done , That's it Strong type language .Python Rarely implicitly convert variable types , therefore Python It's a strong type of language .
  • The key to the judgment of strong type language and weak type reason is Will implicit language type change occur . The strong type reason may be slightly slower than the weak type language in speed , But the rigor brought by strong type definitives avoids unnecessary mistakes .
  • Strong languages include :Java、.net、Python、C++ Other languages . among Python It's dynamic language , Is a strongly typed definition language , Is a type safe language ,Java It's a static language , Is a strongly typed definition language , It's also a type safe language ; Weakly typed languages include :VB,PHP,JavaScript Other languages . among VBScript It's dynamic language , It's a type of insecurity .

Dynamic language 、 The difference between static languages :

  • Dynamic type language Dynamic languages are languages that do data type checking only during runtime , That is to say, dynamic type language programming , Never assign a data type to any variable , The language will be assigned to variables the first time , Record data types internally **.Python and Ruby Is a typical dynamic type language , Other scripting languages such as VBScript It's more or less dynamic .
  • Static type language : Static type languages are the opposite of dynamic classes , Its data type is checked during compilation , That is to say, the data type of all variables should be declared when writing the program ,C/C++ Is a typical representative of static type language , Other static languages include C#、Java etc. .
  • The distinction between dynamic language and static language , It's all about Whether the data type is checked during runtime or during compilation .

Compiler language 、 The difference between interpretative languages :

  • Compiler language You need to translate a program directly into machine code ( about C/C++ This non platform language ) Or middle size (Java This cross platform language , The virtual machine is needed to print the middle code into machine code ). Generally, it needs to be compiled (compile)、 link (linker) These two steps . Compiling is to compile source code into machine code , Link is to connect the machine code of each module with the dependency library to generate the executable file .
  • Explanatory language Use the interpreter to interpret the source line by line into machine code and execute it immediately , There will be no overall compilation and link processing , Compared with compiled language, it saves a process .
  • One is like having a meal and waiting for the dishes to be served , One is like eating hot pot , Wash and eat , The timing is different .
  • The advantages of interpretive language : Cross platform is easy , Just provide a platform specific interpreter ; shortcoming : Explain it every time you run it , Not as good as compiled languages in performance .
  1. Explain and compile programming languages briefly ?

Please refer to the previous explanation .

  1. Python The types of interpreter and related features ?
  • CPython The official version of the interpreter . This interpreter uses C Language development , So called CPython. Run on the command line python That is to start. CPython Interpreter . CPython Is the most widely used Python Interpreter .
  • IPython:IPython Is based on CPython An interactive interpreter on top , in other words ,IPython It's just a little bit more interactive , But to perform Python Code functions and CPython It's exactly the same .CPython use >>> As a prompt , and IPython use In [ Serial number ]: As a prompt .
  • PyPy: its The goal is speed of execution .PyPy use JIT technology , Yes Python Dynamic compilation of code ( Notice it's not an explanation ), So it can be significantly improved Python Code execution speed . most Python Code can be found in PyPy Run under , however PyPy and CPython Some are different , This leads to the same Python Code execution under two interpreters may have different results .
  • Jython:Jython Is running on the Java On the platform Python Interpreter , You can directly Python Code compiled into Java Bytecode execution .
  • IronPython:IronPython and Jython similar , It's just IronPython It's running at Microsoft .Net On the platform Python Interpreter , You can directly Python Code compiled into .Net Bytecode .
  1. Tell me what you know Python3 and Python2 The difference between ?

code Python2 The default encoding for is asscii, It also leads to Python2 One of the reasons we often encounter coding problems in , As for why we use asscii As default encoding , The reason lies in Python The language was not born yet Unicode.Python3 By default UTF-8 As default encoding , So you don't have to write at the top of the file # coding=utf-8 了 .

character string :Python2 The type of Chinese characters ,str: The sequence of bytes that have been encoded ,unicode: Text characters before encoding ; and Python3 The type of Chinese characters ,str: Code of unicode Text character ,bytes: Sequence of bytes before encoding .

You can think of a string as having two states , That is, text status and bytes ( Binary system ) state .Python2 and Python3 Both character types in correspond to these two states respectively , And then encode and decode each other . Encoding is to convert a string into bytecode , It's about the internal representation of strings ; Decoding is the conversion of bytecode to string , Display bits as characters .

stay Python2 in ,str and unicode There are encode and decode Method . But not recommended for str Use encode, Yes unicode Use decode, This is a Python2 Defects in design .Python3 It's optimized ,str only one encode Method to convert a string to a bytecode , and bytes There is only one decode Method to convert bytecode to a text string .

printPython2 Medium print Is the statement ;Python3 Medium print Is the function . for example :

# py2
>>> print("hello", "world")
('hello', 'world')
# py3
>>> print("hello", "world")
hello world

This example is obvious , stay py2 in ,print The statement is followed by a tuple object , And in the py3 in ,print Function can receive multiple position parameters . If you want to Python2 Zhongba print When a function uses , Then you can import future Module print_function.

importpython2 The default is to import modules and packages according to the relative path ,python3 The default is to import by absolute path .

import The understanding of the :python2 and python3 adopt import The difference between the import module and the package

input:Python3:input The parsing input is str Character ;Python2:input The parsing input is int type ,raw_input The parsing input is str type .

Algorithmic symbols : stay Python2 in ,/ Perform traditional division , Perform truncation division on integers , Floating point performs floating-point division ( Keep the decimal part , Even if you divide );// perform Floor division , Truncates the remainder and returns an integer for the integer operand , If any of the operands are floating-point numbers , Returns a floating-point number . stay Python3 in ,/ Always perform true Division , Regardless of the type of operand , Will return a floating-point result with any remainder ;// perform Floor division , Truncates the remainder and returns an integer for the integer operand , If any of the operands are floating-point numbers , Returns a floating-point number .

int/longPython3 in , There is only one integer type int, Most of the time , It's very much like Python2 The long shape of Li .Python2 There's something for non floating point numbers int and long type .int The maximum value of type cannot exceed sys.maxint, And this maximum is platform related .

True and False stay Python2 in ,True and False It's two global variables ( name ), In numerical terms, they correspond to 1 and 0, Since it's a variable , Then they can point to other objects .Python3 Fixed this bug ,True and False Change to two keywords , Always point to two fixed objects , It is not allowed to be reassigned .

iterator stay Python2 Many of the built-in functions and methods that return list objects in Python3 All changed to return objects similar to iterators , Because the iterator's lazy loading feature makes it more efficient to operate big data .

for example :Python2 Use in xrange() To create an iterator object , Use range() Create a list Array ( To generate a large sequence of numbers , use xrange than range It's a lot better , Because it doesn't need to open up a large memory space );Python3 Use in range() Create iterator object , Removed xrange() Method .

in addition , Of dictionary objects dict.keys()、dict.values() Methods are no longer returned to the list , But with an iterator like view Object returns . Higher order function map、filter、zip None of the returned objects are list objects .Python2 The iterator of must implement next Method , and Python3 Changed to __iter__()、next.

nonlocal: stay Python2 You can use keywords in functions global Declare a variable as a global variable , But in nested functions , It's impossible to declare a variable as a nonlocal variable , stay Pyhon3, New keyword nonlcoal, Commonly used in closures , Make the variable use the outer variable with the same name .

LEGB Understanding of scope :python3 Of local, global, nonlocal analysis

  1. Python3 and Python2 in int and long difference ?

Please refer to the previous explanation .

  1. xrange and range The difference between ?

Please refer to the explanation above .

本文为[Yngz_ Miao]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database