[Python] 50 interview questions sorting

Article Directory

The difference between lists and tuples in Python

insert image description here

Main functions of Python

  • Python is an interpreted language. Unlike languages ​​such as C, Python does not need to be compiled before it can be run .
  • Python is a dynamic language , when you declare a variable or similar, you don't need to declare the type of the variable .
  • Python is suitable for object-oriented programming because it allows the definition of classes as well as composition and inheritance .
  • Python does not have access instructions (like C++'s public, private).
  • In Python, functions are first-class objects. They can be assigned to variables. Classes are also first-class objects
  • Writing Python code is fast, but running it is slow . Python allows C-based extensions , such as the numpy library.
  • Python can be used in many fields. Web application development, automation, mathematical modeling, big data applications and more. It is also often used as "glue" code.

What is pep?

PEP stands for Python Enhancement Proposal . It is a set of rules specifying how to format Python code for maximum readability .

How to manage memory in Python?

TODO: check here

  • Memory management in python is managed by the Python private heap space. All Python objects and data structures are located on the private heap. Programmers do not have access to this private heap. The python interpreter takes care of this.
  • Heap space allocation for Python objects is done by Python's memory manager. The core API provides some tools for programmers to write code.
  • Python also has a built-in garbage collector which reclaims all unused memory and makes it available for heap space.

What are namespaces in Python?

A namespace is a naming system used to ensure that names are unique to avoid naming conflicts.

What is PYTHONPATH?

  • It is an environment variable used when importing modules .
  • Whenever a module is imported, the PYTHONPATH is also looked up to check whether the imported module exists in the respective directories.
  • The interpreter uses this to determine which modules to load.

What are python modules? What are the commonly used built-in modules in Python?

Python modules are .py files that contain Python code.
This code can be a function class or a variable.
Some commonly used built-in modules include: sys、math、random、data time、JSON.

What are local and global variables in Python?

  • Global Variables: Variables declared outside a function or in the global space are called global variables. These variables can be accessed by any function in the program.

  • Local Variables: Any variable declared inside a function is known as a local variable. This variable exists in local space, not global space.

Is python case sensitive?

yes . Python is a case sensitive language.

Q12. What is type conversion in Python?

Type conversion refers to converting one data type to another data type.

int()  - 将任何数据类型转换为整数类型

float()  - 将任何数据类型转换为float类型

ord()  - 将字符转换为整数

hex() - 将整数转换为十六进制

oct()  - 将整数转换为八进制

tuple() - 此函数用于转换为元组。

set() - 此函数在转换为set后返回类型。

list() - 此函数用于将任何数据类型转换为列表类型。

dict() - 此函数用于将顺序元组(键,值)转换为字典。

str() - 用于将整数转换为字符串。

complex(real,imag)  - 此函数将实数转换为复数(实数,图像)数。

How to install Python and set path variables on Windows?

To install Python on Windows, follow these steps:

  • Install python from the following link: https://http://www.python.org/downloads/
  • After downloading, install it on your PC. Find where PYTHON is installed on your PC using the following command at the command prompt: cmd python.
  • Then go to advanced system settings and add new variable and name it PYTHON_NAME and paste the copied path.
  • Find the Path variable, select its value and choose Edit.
  • If the value does not exist, add a semicolon at the end of the value and type %PYTHON_HOME%

Is indentation required in python?

Indentation is required by Python. It specifies a block of code.
All code in loops, classes, functions, etc. is specified in indented blocks. Usually this is done with four space characters.
If your code is indented unnecessarily, it won't execute correctly and will throw an error as well.

What is the difference between Python arrays and lists?

Arrays and lists in Python have the same way of storing data.
However, an array can contain only a single data type element whereas a list can contain any data type element.

What are functions in Python?

A function is a block of code that is executed only when called. To define a function in Python, you need to use the def keyword.

What is __init__?

  • __init__ is a method or structure in Python.
  • This method is automatically called to allocate memory when a new object/instance of the class is created.
  • All classes have an __init__ method.

What are lambda functions?

A lambda function is also called an anonymous function. The function can contain any number of parameters , but there can only be one statement that performs an operation.lambda [arg1 [,arg2,.....argn]]:expression

lambda attribute

  • The lambda function is anonymous:
    the so-called anonymous function, in layman's terms, is a function without a name. Lambda functions don't have names.
  • The lambda function has input and output:
    the input is the value passed into the parameter list argument_list, and the output is the value calculated according to the expression expression.
  • The lambda function has its own namespace:
    it cannot access parameters outside its own parameter list or in the global namespace, and can only complete very simple functions.
    Common lambda function examples:
lambda x, y: x*y			# 函数输入是x和y,输出是它们的积x*y
lambda:None					# 函数没有输入参数,输出是None
lambda *args: sum(args)		# 输入是任意个数参数,输出是它们的和(隐性要求输入参数必须能进行算术运算)
lambda **kwargs: 1			# 输入是任意键值对参数,输出是1

Advanced usage of lambda functions

Used in conjunction with map

map()function:

  • Description:
    map() will map the specified sequence according to the provided function.
    The first parameter function calls the function function with each element in the parameter sequence, and returns a new list containing each return value of the function function.

  • grammar:
    map(function, iterable, ...)

  • Parameters:
    function ----> function
    iterable ----> one or more sequences

  • Return value:
    Python 2.x returns a list
    Python 3.x returns an iterator

  • example

a = list(map(lambda x: x ** 2, [1, 2, 3, 4]))
# [1, 4, 9, 16]
b = list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
# [3, 7, 11, 15, 19]

Combined with reduce

  • Description:
    reduce()The function will accumulate the elements in the parameter sequence.
    The function performs the following operations on all the data in a data set (linked list, tuple, etc.): use the function function (with two parameters) passed to reduce to operate on the first and second elements in the set, and get The result is then calculated with the third data using the function function, and finally a result is obtained.

  • grammar:
    reduce(function, iterable[, initializer])

  • Parameters:
    function ----> function with two parameters
    iterable ----> iterable object
    initializer ----> optional, initial parameter

  • Return Value:
    Returns the result of the function calculation.

  • Example:

a = reduce(lambda x, y: x * 10 + y, [1, 3, 5, 7, 9])
# 13579

Used in conjunction with sorted

  • Description:
    sorted()The function sorts all iterable objects.

  • sortand sorteddifference:

    • sortis a method of list
    • And sortedcan sort all iterable objects .
    • The method of list sortreturns an operation on an existing list, and has no return value ;
    • The built-in function sortedmethod returns a new list instead of operating on the original one.
  • grammar:
    sorted(iterable[, cmp[, key[, reverse]]])

  • Parameter Description:

    • iterable ----> iterable object.
    • cmp ----> comparison function, this has two parameters, and the values ​​of the parameters are all taken from the iterable object. The rules that this function must abide by are: if it is greater than, return 1; if it is less than, return -1; if it is equal, return 0.
    • key ----> is mainly used for comparing elements, only one parameter, the parameter of the specific function is taken from the iterable object, specify an element in the iterable object to sort.
    • reverse ----> sorting rules, reverse = True descending, reverse = False ascending (default).
  • Return Value:
    Returns the reordered list.

  • Example:

dict={
    
    'a':1,'b':2}
ans = sorted(dict.items(), key = lambda x:x[1], reverse = True)

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]  
sorted(students, key=lambda student : student[2])   # sort by age  
# [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]  

Used in conjunction with filter

  • Description:
    The filter() function is used to filter the sequence, filter out elements that do not meet the conditions, and return a new list composed of elements that meet the conditions.

It receives two parameters, the first is a function, and the second is a sequence. Each element of the sequence is passed as a parameter to the function for judgment, and then returns True or False, and finally puts the element that returns True into a new list.

  • Syntax:
    filter(function, iterable)
  • Parameters:
    function ----> judgment function.
    iterable ----> iterable object.
  • Return value:
    Pyhton2.7 returns a list, and Python3.x returns an iterator object. For details, please refer to: Python3 filter() function
  • Example:
# ===========一般用法:===========
# 1、过滤出列表中的所有奇数
def is_odd(n):
	return n % 2 == 1
		 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
# 结果: [1, 3, 5, 7, 9]

# ===========匿名函数用法:===========
# 2、将列表[1, 2, 3]中能够被3整除的元素过滤出来
newlist = filter(lambda x: x % 3 == 0, [1, 2, 3])
print(list(newlist))

What is self in Python?

  • self is an instance or object of the class.
  • In Python, self is included in the first argument.
  • However, this is not the case in Java, where it is optional.
  • It helps to distinguish methods and properties of classes with local variables.
  • The self variable in the init method refers to the newly created object, while in other methods it refers to the object whose method was called.

Distinguish between break, continue and pass?

insert image description here

What does [::-1] mean?

[:: - 1]Used to reverse the order of an array or sequence.

Q22. How to randomize the elements in a list in Python?

You can use the shuffle function to shuffle list elements. Examples are as follows:
insert image description here

##

What are python iterators?

Iterators are objects that can be traversed or iterated over.

Q24. How to generate random numbers in Python?

The random module is the standard module for generating random numbers. The method is defined as:

The random.random() method returns a floating point number in the range [0,1]. This function generates random floating point numbers. The method used by the random class is to hide the bound method of the instance.
An instance of Random can be used to show a multithreaded program that creates different thread instances. Other random generators used in it are:

  • randrange(a,b): It selects an integer and defines the range between [a,b]. It returns elements by randomly selecting elements from the specified range. It doesn't build range objects.
  • uniform(a,b): it selects a floating point number defined in the range [a,b)
  • normalvariate(mean,sdev): It is used for normal distribution, where mean is mean and sdev is sigma for standard deviation.

Use and instantiate the Random class to create an independent multiple random number generator.

Q25. What is the difference between range and xrange?

In most cases, xrange and range are functionally identical. They both provide a way to generate a list of integers, the only difference being that range returns a Python list object and x range returns an xrange object. This means that xrange does not actually generate a static list at runtime. It creates values ​​on demand using a special technique called yielding. This technique works with a type of object called a generator. So if you have a really huge list, consider xrange.

Q27. What are pickling and unpickling?

The Pickle module takes any Python object and converts it to a string representation and dumps it to a file using the dump function, a process called pickling. The process of retrieving raw Python objects from stored strings is called unpickling.

Q28. What is a generator in python?

A function that returns an iterable itemset is called a generator.

string case

Capitalize the first letter: capitalize()The function can capitalize the first letter of the string. If the string already contains capital letters at the beginning, then it will return the original string.
All lowercase: You can use the l ower()function.

What are Documentation Docstrings in Python?

Docstrings are not actually comments, they are docstrings. These docstrings are enclosed in triple quotes. They are not assigned to any variable, so they are also sometimes used for comments.

Q33. What are the functions of is, not and in in operators?

Operators are special functions that compare one or more values ​​and produce corresponding results. where is: returns true when 2 operands are true (eg: "a" is 'a')

not: returns the reciprocal of the boolean value

in: checks whether an element exists in a sequence

Q34. What is the usage of help() and dir() functions in Python?

Both functions Help() and dir() are directly accessible from the Python interpreter and are used to view merged dumps of built-in functions.

help() function: The help() function is used to display the documentation string, and you can also view usage information related to modules, keywords, attributes, etc.

dir() function: The dir() function is used to display the defined symbols.

Q35. Why doesn't all allocated memory be cleared when Python exits?

In particular, Python modules that have circular references to other objects or objects referenced from the global namespace are not deallocated or freed when Python exits.

Those parts of memory reserved by the C library cannot be deallocated.

On exit, Python tries to deallocate/destroy all other objects thanks to its own efficient cleanup mechanism.

Q36. What is a dictionary in Python?

A built-in data type in Python is called a dictionary. It defines a one-to-one relationship between a key and a value. A dictionary contains a pair of keys and their corresponding values. Dictionaries are indexed by keys.

Q37. How to use the ternary operator in python?

The ternary operator is an operator used to display conditional statements. This contains true or false values ​​for which the statement must be evaluated. Its basic syntax is:

The ternary operator is an operator used to display conditional statements. This contains true or false values ​​for which the statement must be evaluated. Its basic syntax is:

[on_true] if [expression] else [on_false] x,y = 25,50big = x if x <y else y

Q38. Why use *args, **kwargs?

We use *args when we are not sure how many arguments to pass to a function, or when we want to pass a stored list or tuple of arguments to a function. kwargs is used when we don't know how many keyword arguments to pass to a function, or it can be used to pass the values ​​of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you can also use bob and *billy.

Q40, split(), sub(), subn() functions in Python.

If you want to modify a string, Python's "re" module provides 3 methods. they are:

split() - "splits" the given string into a list using a regex pattern.

sub() - finds all substrings matched by a regex pattern and replaces them with a different string

subn() − It is similar to sub() and also returns new string.

Q41. What is a negative index and what is its function?

Sequences in Python are indexed, which consist of positive and negative numbers. Positive numbers use '0' as the first index and '1' as the second index, which the process continues to use.

Negative numbers start with an index of '-1', indicating the last index in the sequence, '-2' as the second-to-last index, and the sequence advances like a positive number.

Negative indices are used to remove any newlines from the string, and allow the string to except the last character given as S[:-1]. Negative indices are also used to show that the indices represent strings in the correct order.

Q43. How to delete files in Python?

To delete a file in Python, you need to import the OS module. Afterwards, you need to use the os.remove() function.

Q44. What is the built-in type of python?

The built-in types in Python are as follows: Integer, Float, Complex, String, Boolean, etc.

Q45. What are the functions for manipulating Python lists in NumPy?

Python lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python's list comprehensions make them easy to construct and manipulate.

They have certain limitations: they don't support "vectorized" operations like pixelated addition and multiplication, and the fact that they can contain objects of different types means that Python must store type information for each element, and must perform type dispatch code while operating on each element.

NumPy is not only more efficient; it's also more convenient. You get a lot of vector and matrix operations for free, which sometimes saves unnecessary work. They are also effectively implemented.

NumPy arrays are faster, and you can use NumPy, FFT, convolution, fast search, basic statistics, linear algebra, histograms, and more built in.

Q46. How to add values ​​to a python array?

Elements can be added to an array using the append(), extend() and insert(i, x) functions.

Q47. How to delete the value of python array?

Array elements can be removed using the pop() or remove() methods. The difference between these two functions is that the former returns the deleted value while the latter does not.

Q48. Does Python have the concept of OOps?

Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. At the same time, Python can be regarded as a procedural language and a structural language.

Q49. What is the difference between deep copy and shallow copy?

Use a shallow copy when creating a new instance type and preserve the copied values ​​in the new instance. A shallow copy is used to copy a reference pointer just like copying a value. These references point to the original object, and changes made in any member of the class will also affect the original copy of it. Shallow copying allows faster program execution, depending on the size of the data used.

A deep copy is used to store copied values. A deep copy does not copy the reference pointer to the object. It references an object, and stores new objects that some other objects point to. Changes made in the original copy do not affect any other copies that use the object. A deep copy slows down the execution of the program because some copy is created for each object being called.

Q50. How to implement multithreading in Python?

Python has a multithreading library, but the effect of using multithreading to speed up code is not so good,

Python has a structure called the Global Interpreter Lock (GIL). The GIL ensures that only one "thread" can execute at a time. One thread acquires the GIL to perform related operations, and then passes the GIL to the next thread.

Although it looks like the program is being executed in parallel by multiple threads, they are actually just taking turns using the same CPU core.

All these GIL passes add overhead to execution. This means that multithreading does not make the program run faster.

Guess you like

Origin blog.csdn.net/D2Ooo/article/details/127150680