程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Can you do those tricky interview questions for famous enterprises -- python100 interview questions

編輯:Python

python Basic questions ( There are surprises at the end of the article , Receiving interview questions )

1. Conversion between bases

Hexadecimal conversion can adopt the way of built-in function to convert data , You can also use int To convert , It is to convert the number to be converted according to a hexadecimal rule , The final conversion results are int type

number = 20
# Mode one
# Binary system
print(bin(number))
# octal
print(oct(number))
# Hexadecimal
print(hex(number))
# Decimal system
print(int(number))
# Mode two , Can only be converted to the last int type
# Convert the number into int type
print(int(str(number), base=8))
# Convert a number to... In hexadecimal int type
print(int(str(number), base=16))
# take 0b Binary string is converted to int Type digital
print(int(str(bin(number)), base=2))
0b10100
0o24
0x14
20
16
32
20

It should be noted that , stay python in , Binary system 、 octal 、 Hexadecimal will be displayed in decimal system when it is output , But don't pay too much attention

b_number = 0b10100
print(b_number)
o_number = 0o24
print(o_number)
h_number = 0x14
print(h_number)

2. Maximum recursion

The following simple function shows the maximum number of recursions

def recursion(n):
print(n)
n += 1
recursion(n)
recursion(1)

suffer python Different versions , The maximum recursion number is also different

python2.7: 1000, In the 1000 An exception will appear when this function is called for the second time
python3.6: 998, stay 998 An exception will appear when this function is called for the second time 

You can manually set the number of maximum recursions

import sys
sys.setrecursionlimit(1200)

Now find , When the maximum recursion number is set to 1200 when ,python2.7 Will be in 1200 Time error , but python3.6 Will be in 1198 Time error , Relatively few 2 Time , You can launch , The default maximum number of recursions should be 1000( If the first function call is included ).

3.and、not、or Operator priority

object Return results Priority order not xif x is false,then True,else False1x and yif x is false,then x,else y2x or yif x is false,then y,else x3
v1 = 1 or 3 # 1
v2 = 1 and 3 # 3
v3 = 0 and 2 and 1 # 0
v4 = 0 and 2 or 1 # 1
v5 = 0 and 2 or 1 or 4 # 1
v6 = 0 or False and 1 # False
1
3
0
1
1
False

It is important to note that in python in ,0 It's also a representative False

4. Ternary operator , Ternary operator

stay python The ternary operator with the following comments does not exist in , But it is replaced by the ternary operator , You can write a simple conditional branch statement on one line , It is suitable for scenarios that need to simplify the code , And it is faster than multi line branching .

a = 10
# print(a > 2 ? a : 0)
print(a if a > 2 else 0)

5.python2 And python3 difference

1.python2 True、False Can be used as a variable , It can be assigned and valued ,python3 Do not place , True、False As a keyword, it cannot be modified

True = 1
print(True)
False = 0
print(False)

python2

python3

True = 1
^
SyntaxError: can't assign to keyword

2.python2 By default ASCII code , For Chinese, you need to manually add document header comments , python3 You don't need to

print(' Hello ')

python2

File "/home/ts/flask_study/interview/05python2 and python3 The difference between .py", line 12
SyntaxError: Non-ASCII character '\xe4' in file /home/ts/flask_study/interview/05python2 and python3 The difference between .py on line 12, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Need to be in py Add the following note at the top of the file

# -*- coding:utf-8 -*-

python3: It doesn't affect

 Hello 

3.python2 Of range Return to one list, Resource consumption is high ,python3 Returns an iteratable object , Less resource consumption , You can use for Loop the iterative output of the result ,python3 Of range To replace the xrange.

data = range(10)
print(data)
print(type(data))
from typing import Iterable, Iterator, Generator
print(isinstance(data, Iterable))
print(isinstance(data, Iterator))
print(isinstance(data, Generator))

python2

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<type 'list'>

python3

range(0, 10)
<class 'range'>
True
False
False

4.python3 introduce nonlocal keyword , It is convenient for internal functions to read and modify the value of external functions , When the internal function reads and modifies the value of the external function , Then the external function and internal function form a closure

def outter():
number = 10
def inner():
nonlocal number
number += 1
print(number)
return inner
outter()()

python2

UnboundLocalError: local variable 'number' referenced before assignment

python3

5.xreadlines、readlines Read the file ,python2 There is xreadlines, The file object is returned , Less resource consumption ,python3 nothing xreadlines, python2、python3 Back to readlines It's all one list, It is suggested that you can iterate directly open The object of acquisition

import os
file_path = os.path.join(os.path.dirname(__file__), "01 Hexadecimal conversion .py")
print(file_path)
with open(str(file_path), mode="r") as f:
print(f)
print(type(f))
# print(isinstance(f, Iterable))
for line in f:
print(line)
# lines = f.xreadlines()
lines = f.readlines()
print(lines)
print(type(lines))

More to be updated

6. The Boolean value is False Value

print(bool(0))
print(bool(None))
print(bool([]))
print(bool({}))
print(bool(""))
print(bool(0j))

7. character string 、 list 、 Tuples 、 Every commonly used Dictionary 5 A way ?

character string

str_data = 'adminasdasd asdasd'
# Count the number of occurrences of elements in the string
print(str_data.count('a'))
# Capitalize all
print(str_data.upper())
# What does it start with , You can specify where to start
print(str_data.startswith('a'))
# Intercepting string , More use
print(str_data.split('a'))
# Capitalize the first letter only at the beginning of the string
print(str_data.capitalize())
# Each word in the string is capitalized
print(str_data.title())
# String center Fill in the blanks before and after
print(str_data.center(22))
# The string is preceded by 0
print(str_data.zfill(22))
5
ADMINASDASD ASDASD
True
['', 'dmin', 'sd', 'sd ', 'sd', 'sd']
Adminasdasd asdasd
Adminasdasd Asdasd
adminasdasd asdasd
0000adminasdasd asdasd

list

list_data = [1,2,3,4, [5,6]]
# Additive elements
list_data.append(11)
print(list_data)
# Shallow copy list data , When modifying variable objects , The original object will change
copy_list_data = list_data.copy()
print(copy_list_data)
copy_list_data[4].append(4)
print(list_data)
print(copy_list_data)
# Delete the element corresponding to the value
list_data.remove(3)
print(list_data)
# Count the number of occurrences of an element
print(list_data.count(1))
# The two lists merge
list_data.extend(copy_list_data)
print(list_data)
# Sort the list , Elements need to be of the same type , The default is ascending
# list_data.sort()
print(list_data)
# Insert the element in the specified subscript
list_data.insert(0, -1)
print(list_data)
# Delete the element corresponding to the subscript
list_data.pop(4)
print(list_data)
[1, 2, 3, 4, [5, 6], 11]
[1, 2, 3, 4, [5, 6], 11]
[1, 2, 3, 4, [5, 6, 4], 11]
[1, 2, 3, 4, [5, 6, 4], 11]
[1, 2, 4, [5, 6, 4], 11]
1
[1, 2, 4, [5, 6, 4], 11, 1, 2, 3, 4, [5, 6, 4], 11]
[1, 2, 4, [5, 6, 4], 11, 1, 2, 3, 4, [5, 6, 4], 11]
[-1, 1, 2, 4, [5, 6, 4], 11, 1, 2, 3, 4, [5, 6, 4], 11]
[-1, 1, 2, 4, 11, 1, 2, 3, 4, [5, 6, 4], 11]

Tuples

tuple_data = (1,2,3,4,5,1,5)
# Count the number of occurrences of elements
print(tuple_data.count(1))
# Get the element of a subscript
print(tuple_data.index(1))

Dictionaries

dict_data = {"name":"tom", "age":10, "gender":"man"}
dict_data2 = {"city":"nanjing"}
# Get all of the dictionary keys
print(dict_data.keys())
# Get all of the dictionary values
print(dict_data.values())
# Get all key value pairs of the dictionary , Display in tuple form
print(dict_data.items())
# Merge two dictionaries
dict_data.update(dict_data2)
print(dict_data)
# Get the elements in the dictionary , Default values can be set
print(dict_data.get('name', None))
# Delete elements from Dictionary
dict_data.pop('age')
print(dict_data)
# Generate new dictionary , Take out the dictionary key, Set default value value , Default value by None
print(dict_data.fromkeys(dict_data.copy(), "no data"))
# Delete elements from Dictionary , Delete the last element by default
dict_data.popitem()
print(dict_data)
# Get the value of the element in the dictionary , When corresponding key When it does not exist, it will actively set the corresponding key And return the set value , When key In existence , This function is related to get Consistent use
print(dict_data.setdefault('age', 10))
print(dict_data)
# Empty dictionary
dict_data.clear()
print(dict_data)
dict_keys(['name', 'age', 'gender'])
dict_values(['tom', 10, 'man'])
dict_items([('name', 'tom'), ('age', 10), ('gender', 'man')])
{'name': 'tom', 'age': 10, 'gender': 'man', 'city': 'nanjing'}
tom
{'name': 'tom', 'gender': 'man', 'city': 'nanjing'}
{'name': 'no data', 'gender': 'no data', 'city': 'no data'}
{'name': 'tom', 'gender': 'man'}
10
{'name': 'tom', 'gender': 'man', 'age': 10}
{}

8.lambda Usage method and usage scenario

def sum(m,n):
return m+n
print(sum(1,2))
sum2 = lambda m,n:m+n
print(sum2(1,2))

lambda It is mainly aimed at simplifying code operation of functions , But only simple code simplification , Complex code is not recommended lambda,

Use scenarios

1.map、reduce、filter Etc. for sequence processing

l = list(range(1, 10))
data = map(lambda n:n*n, l)
print(list(data))
from functools import reduce
data = reduce(lambda m,n:m*n, l)
print(data)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
362880

2.lambda And list Combination , Be careful lambda Only the last status will be recorded , The status of the intermediate process will not be recorded

l2 = [lambda:i for i in range(10)]
print(l2[0]())
print(l2[3]())

9.pass The role of

pass Mainly in the process of code implementation , I haven't figured out how to realize it for the time being , Usually in function 、 Methods are used more , Avoid reporting errors because there is nothing in the function or method

10.*arg and **kwarg effect

In a function or method , *args Will convert elements to tuples , **kwargs Will x=y Similar elements are converted into dictionaries

def run(*args, **kwargs):
print(args)
print(kwargs)
run(1,2,a=1,b=2)
(1, 2)
{'a': 1, 'b': 2}

Click on Interview questions receive Tencent documents - Online document https://docs.qq.com/doc/DT09DZ1hSYkJORURY


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved