Python interview questions--3 (15 questions)

Table of contents

What are generators in Python? How to create a generator?

Explains recursive functions in Python and when to use them.

What is the difference between iterators and iterables in Python?

What are modules and packages in Python? What's the difference?

How to handle exceptions in Python? Explain how try-except-else-finally blocks work.

The lazy mechanism of generators in python

The difference between inheritance and decorators

The difference between adapter mode and decorator mode

 What does "self" in a class refer to?

What is the difference between a list and an array?

Give some examples of mutable and immutable objects?

What is pickling?

What is the difference between a dictionary and JSON?

What is the difference between a module and a package?


What are generators in Python? How to create a generator?

Answer: A generator is a special kind of function that uses the yield statement to produce a value, and execution can be paused and resumed. Generators save memory by yielding values ​​one by one on demand, rather than all at once.

Generators can be created in two ways:

Using a generator function: A generator function is an ordinary function that uses a yield statement to produce a value. When a generator function is called, it returns a generator object. Each time the generator's next() method is called or iterated, it continues execution from where it left off until it encounters the next yield statement.

Using generator expressions: Generator expressions are a syntax similar to list comprehensions, but return a generator object instead of a list. Generator expressions use parentheses instead of square brackets.

Explains recursive functions in Python and when to use them.

Answer: A recursive function is a function that calls itself . Recursive functions are often used in situations where they can be broken down into subproblems of the same problem. Recursive functions must define a stopping condition to prevent infinite recursion .

Use cases for recursive functions include:

  • Traversal of trees and graphs: Recursive functions can be used to traverse the nodes of a tree or graph in order to visit and process each node.
  • Mathematical problems: Some mathematical problems are recursive in nature, such as factorial, Fibonacci sequence, etc.
  • Divide and Conquer Algorithms: Divide and conquer algorithms typically use a recursive function to break down the problem into smaller subproblems and combine the results.

What is the difference between iterators and iterables in Python?

Answer: Iterators and iterable objects are two related concepts in Python that deal with iteration.

Iterable objects: Objects that implement the __iter__() method, or objects that implement the __getitem__() method and support indexing. Iterable objects can be traversed through iterators .

An iterator is an object that implements the __iter__() and __next__() methods. Iterators can iterate over an iterable and return each element in the sequence. The iterator uses lazy calculation, that is, it calculates and returns each time an element is requested, thereby saving memory.

The difference is as follows:

An iterable object is a collection whose elements can be iterated through an iterator.

An iterator is an object that iterates over an iterable and returns elements one by one .

Iterable objects can use the iter() function to obtain an iterator.

 

The iterator uses the next() method to get the next element, and a StopIteration exception is raised when there are no elements.

Example:

my_list = [1, 2, 3, 4]

iterable = iter(my_list) # get iterator

print(next(iterable)) # output: 1

print(next(iterable)) # output: 2

print(next(iterable)) # output: 3

In the above example, my_list is an iterable object and its iterator iterable can be obtained using the iter() function. Then, access the elements of the iterator one by one by calling the next() method .

What are modules and packages in Python? What's the difference?

Answer: In Python, a module is a file containing Python code to organize and reuse code. A package is a directory containing multiple modules for better organization and management of related modules. Modules can be imported through the import statement and use the functions, classes, and variables in them. A package is a directory containing an __init__.py file, which can contain multiple modules and other subpackages.

How to handle exceptions in Python? Explain how try-except-else-finally blocks work.

Answer: In Python, exceptions can be handled using try-except-else-finally blocks. The try block contains code that may throw an exception. If an exception occurs, it will be handled according to the matching except block. If no exception occurs, the code in the else block will be executed. The code in the finally block is always executed regardless of whether an exception occurs or not.

It works as follows:

If the code in the try block throws an exception, the matching except block is executed, and the else block and finally block are skipped.

If the code in the try block does not throw an exception, the else block is executed and the finally block is skipped.

The code in the finally block is always executed regardless of whether an exception occurs or not.

Python programming interview questions (20 cases)_iterator

 

The lazy mechanism of generators in python

The generator has a lazy mechanism, and it will only be given to you when you need it (one by one), instead of giving you all the words at once.

Example: Xiaoming and Xiaohong want to eat eggs. One day, Xiaoming and Xiaohong went to sell eggs on the street. When they got home, Xiaoming bought a basket of eggs, about 100. Xiaohong bought a hen. Chicken (assuming that all external conditions are removed, the hen can lay eggs without eating or drinking (during the egg laying period) and can live forever, as long as the owner needs it, she can lay eggs at any time).

Xiao Ming has a basket of eggs, so he can eat a few eggs, a dozen eggs, or even a hundred eggs together.

But Xiaohong can only eat one by one, because the hen will only lay eggs for the needs of the owner.

Note: At this time, the behavior of the hen is the inert mechanism of the generator in python , which will only be taken out as needed, and one by one, not all at once. Here is a special note:

Generators are not inexhaustible, they can be exhausted. It's like a chicken laying eggs all the time, but there are periods of laying eggs.
The output in the generator is like the stack in the data structure. The amount of output depends on how much you have in the stack. After the stack is exhausted, it becomes empty, and there is nothing left. Like a bag containing rice, it is impossible to pour out the rice indefinitely when pouring out, only the original rice in the bag can be poured out. Otherwise I want a bag like this too

The difference between inheritance and decorators


The decorator pattern is more flexible than inheritance. Avoiding the bloated inheritance system,
the decorator mode reduces the relationship between classes.
If you want to talk about whether the functions implemented by decorators can be realized by inheritance, I can only say yes, but at the structural level of the code, the decorator pattern is much more flexible than inheritance.

  • The purpose of both the decoration pattern and the inheritance relationship is to expand the functionality of the object, but the decoration pattern can provide more flexibility than inheritance. Decoration mode allows the system to dynamically decide to "paste" a desired "decoration", or "remove" an unnecessary "decoration" .
  • The inheritance relationship is different, the inheritance relationship is static, it is determined before the system runs

Through different specific decoration classes and the arrangement and combination of these decoration classes, designers can create more combinations of different behaviors.
 

The difference between adapter mode and decorator mode

Both the adapter mode and the decorator mode can be modified and enhanced on the basis of the original class file method, but the emphasis is different. The adapter mode
focuses on converting one interface to another interface.
The decorator mode focuses on the enhancement of the original class file method, but The interface is still the same interface

Adapter mode:

Adapter mode: Solve the situation where the original class file (adapter) is similar to the existing requirement (target) but cannot be used directly.
By adding a layer of adapter, the existing interface is enhanced, and the user does not need to know the internal working details of the adapter when using the adapter, so the existing
interface (that is, the adapter) can be directly combined inside the adapter class, and
the adapter is in the adapter The call in is insensitive to the user, and the user only needs to care about the adapter

Decorator pattern:

Decorator mode: Dynamically extend the function of an object without changing the original class file and using inheritance, and wrap the real object by creating a wrapper object, that is, decoration.
Because the decorator only enhances the function of the original class file, the interface of the decorator class and the original class file should be the same. In the decorator mode, the interface is used to standardize the methods of the two to ensure the consistency of the method [in the adapter There is no need to ensure that the interface of the adapter and the adapter are consistent in the mode]
When using the original class file, the user can selectively decorate this class (that is, decorate or not), so the user is aware of the existence of the original class file. Use aggregation to pass in the original class object to be decorated.
When the method of generating subclasses cannot be used for extension. In one case, there may be a large number of independent extensions, and a large number of subclasses will be generated to support each combination, making the number of subclasses grow explosively. Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.

 What does "self" in a class refer to?

"self" refers to the instance of the class itself. This is where we give methods access and the ability to update the object the method belongs to.

What is the difference between a list and an array?

Note: Python's standard library has an array (array) object, but here, I'm referring specifically to the commonly used Numpy array.

Lists exist in python's standard library.

Arrays are defined by Numpy.

Lists can be populated with different types of data at each index.

Arrays require isomorphic elements.

Arithmetic operations on lists add or remove elements from the list.

Arithmetic operations on arrays work in a linear algebra fashion.

Lists also use less memory and have significantly more functionality.

Give some examples of mutable and immutable objects?

Immutable means that state cannot be modified after creation. For example: int, float, bool, string, and tuple.

Mutable means that state can be modified after creation . For example lists (list), dictionaries (dict) and collections (set) .

What is pickling?

Pickling is a common way to serialize and deserialize objects in Python.

The pickle module implements a binary protocol for serializing and deserializing Python object structures. "pickling" is the process of converting a Python object hierarchy into a stream of bytes,

"Unpickling" is the reverse operation, i.e. transforming a stream of bytes (from a binary file or a bytes-like object) back into an object hierarchy . "Pickling" is also called "serialization", "marshalling" or "flattening", while "unpickling" is called "deserialization". To avoid confusion, the terms "pickling" and "unpickling" should be used whenever possible.

What is the difference between a dictionary and JSON?

A Dict is a Python data type that is an indexed but unordered collection of keys and values .

JSON is just a string following a specified format for transferring data .

What is the difference between a module and a package?

Modules are files (or collections of files) that can be imported together.

import sklearn package is a directory of modules.

from sklearn import cross_validation So packages are modules, but not all modules are packages.

Guess you like

Origin blog.csdn.net/qq_38998213/article/details/132513354