In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "summing up 53 interview questions and answers about Python". Interested friends might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "summing up 53 interview questions about Python".
1. What's the difference between lists and tuples?
I've been asked this question in every python or data science interview. Job seekers should know the answer like the back of their hand.
The list is variable. Can be modified after creation.
Tuples are immutable. Once you have created a tuple, you cannot change it
Lists are ordered, are ordered, and are usually objects of the same type. That is, all user names sorted by creation date, ["Seth", "Ema", "Eli"]
Tuples have structures. There may be different data types in each index. That is, database records in memory, (2, "Ema", "2020mur04Mu16") # id, name,created_at
2. What's the difference between "is" and "="?
When I first learned python, I thought they were the same. But there are some bug. Therefore, for recording, is means to check identity, and = = means to check for equality.
It can be explained by an example. Create some lists and assign them to names. Notice that b points to the same object as a below.
A = [1pyrm 2pr 3] b = a c = [1pr 2pr 3]
Check that they are equal and note that they are all equal.
Print (a = = b) print (a = = c) # = > True # = > True
But do they have the same identity? No, no.
Print (an is b) print (an is c) # = > True # = > False
We can verify this by printing its object ID.
Print (id (a)) print (id (b)) print (id (c)) # = > 4369567560 # = > 4369567560 # = > 4369567624
C has different ID from an and b.
3. What is a decorator?
This question is asked in every interview. The question itself deserves another article, but if you can write your own examples step by step, you're ready to answer it.
The decorator allows you to add functionality to an existing function by passing it to the decorator, which executes existing functions and other code.
Write a decorator that logs when another function is called.
Write decorator functions. This requires a function func as an argument. It also defines a function log_function_called that calls func () and executes some code print (f'{func} called.) . Then return the defined function
Deflogging (func): deflog _ function_called (): print (f'{func} called.') Func () return log_function_called
Write other functions that eventually add the decorator (but not yet).
Def my_name (): print ('chris') def friends_name (): print (' naruto') my_name () friends_name () # = > chris # = > naruto
Now add the decorator to both.
Logging def my_name (): print ('chris') @ logging def friends_name (): print (' naruto') my_name () friends_name () # = > called. # = > chris # = > called. # = > naruto
Learn how you can now easily add logs to any function you write simply by adding @ logging to it.
4. How to implement string interpolation?
There are three ways to implement string interpolation without importing the Template class.
Name = 'Chris'# 1. F strings print (f'Hello {name}') # 2.% operator print ('Hey% s% s'% (name, name)) # 3. Format print ("My name is {}" .format ((name)
5. Interpreting range function
Range generates a list of integers that can be used in three ways.
This function takes 1 to 3 parameters. Notice that each usage is wrapped in list parsing so that you can see the generated value.
Range (stop): generates an integer from 0 to "stop".
[i for i in range (10)] # = > [0,1,2,3,4,5,6,7,8,9]
Range (start,stop): generates an integer from "start" to "stop".
[i for i in range (2jre 10)] # = > [2, 3, 4, 5, 6, 7, 8, 9]
Range (start,stop,step): generates integers from "start" to "stop" at intervals of "step".
[i for i in range (2Jing 10jue 2)] # = > [2,4,6,8]
6. Define a class named car with two properties, color and speed. Then create an instance and return the speed.
Class Car: def _ init__ (self, color, speed): self.color = color self.speed = speedcar = Car ('red','100mph') car.speed # = >' 100mph'
7. What is the difference between instance methods, static methods, and class methods in python?
Instance method: accepts the self parameter and is related to a specific instance of the class.
Static methods: use the @ staticmethod decorator, independent of a specific instance, and independent (do not modify class or instance properties)
Class method: accepts the cls parameter and can modify the class itself
Give an example of the difference between a fictional CoffeeShop class.
Class CoffeeShop: specialty = 'espresso' def _ init__ (self, coffee_price): self.coffee_price = coffee_price # instance method def make_coffee (self): print (f'Making {self.specialty} for ${self.coffee_price}') # staticmethod @ staticmethod def check_weather (): print ('Its sunny') # classmethod @ classmethod def change_specialty (cls) Specialty): cls.specialty = specialty print (f'Specialty changed to {specialty}')
The CoffeeShop class has the property specialty, which is set to "espresso" by default. Each instance of CoffeeShop is initialized with the property coffee_price. It also has three methods, instance method, static method and class method.
Initialize the coffee shop instance with coffee_price as 5. Then call the instance method make_coffee.
Coffee_shop = CoffeeShop ('5') coffee_shop.make_coffee () # = > Making espresso for $5
Now call the static method. Static methods cannot modify the state of a class or instance, so they are commonly used for utility functions, such as adding two numbers. We use it to check the weather. Its sunny . Great!
Coffee_shop.check_weather () # = > Itssunny
Now use the class method to modify the coffee shop specialty, and then modify the make_coffee.
Coffee_shop.change_specialty ('dripcoffee') # = > Specialty changed to drip coffeecoffee_shop.make_coffee () # = > Making dripcoffee for $5
Please note that make_coffee used to be used to make espresso, but now you can make drip coffee!
8. Explain how the filter function works
As the name implies, the Filter function works by filtering elements sequentially.
Each element is passed to a function, and if the function returns True, it returns in the order of output, and if the function returns False, it is discarded.
Def add_three (x): if x% 2 = = 0: return True else: return Falseli = [1 add_three 2 3 4 5 5 6 7 8] [i for i in filter (add_three, li)] # = > [2,4,6,8]
Notice how to delete all elements that are not divisible by 2.
9. Is python called by reference or by value?
If you have searched for this question and read the first few pages, be prepared to learn more about semantics. It is best to know only how it works.
Immutable objects such as strings, numbers, and tuples are called by value. Note that after modification is made inside the function, the value of name does not change outside the function. The value of name has been assigned to a new block in memory within the scope of this function.
Name = 'chr'def add_chars (s): s + =' is' print (s) add_chars (name) print (name) # = > chris # = > chr
Mutable objects, such as list, are called by reference. Notice how the list defined outside the function is modified inside the function. The arguments in the function point to the original block where the li value is stored in memory.
Li = [1Magazine 2] def add_element (seq): seq.append (3) print (seq) add_element (li) print (li) # = > [1mai 2,3] # = > [1mai 2,3]
10. How do I undo the list?
Notice how to call reverse () on the list and mutate it. It does not return the mutation list itself.
Li = [print (li) li.reverse () print (li) # = > ['axiomagol]]
11. Explain how the map function works
Map returns a list of return values by applying a function to each element in the sequence.
Def add_three (x): return x + 3li = [1Jing 2jue 3] [i for i inmap (add_three, li)] # = > [4,5,6]
Above, 3 has been added to each element in the list.
twelve。 How does string multiplication work?
Let's look at the result of multiplying the string 'cat' by 3.
'cat' * 3 # = > 'catcatcat'
The string concatenates itself 3 times.
13. How does list multiplication work?
Let's take a look at the result of multiplying the list [1, 1, 2, 2, 3] by 2.
[1pyrrine 2pyr3] * 2 # = > [1pyrrine 2pyr3, 1pyrm2pyr3] 1
The output contains a list of content that has been repeated twice [1 ~ 2 ~ 2 ~ 3].
14. What does "self" mean on the class?
Self refers to an instance of the class itself. This is our ability to give methods access and update the objects to which the method belongs.
Next, passing self to _ _ init _ () enables us to set the color of the instance at initialization time.
Class Shirt: def _ init__ (self, color): self.color = color s = Shirt ('yellow') s.color # = >' yellow'
15. How do I connect lists in python?
Add the two lists together and concatenate them. Note that the functions of arrays are different.
A = [1Jing 2] b = [3Jing 4Jue 5] a + b # = > [1BY 2,3Jet 4JE 5]
16. What's the difference between a shallow copy and a deep copy?
Discuss in the context of mutable objects (lists). For immutable objects, shallow and deep are not important.
Here are three situations.
One is to reference the original object. This points the new name li2 to the same location where li1 points in memory. Therefore, any changes made to li1 will also occur in li2.
Li1 = [['a'], ['b'], ['c']] li2 = li1li1.append (['d']) print (li2) # = > [['a'], ['b'], ['c'], ['d']]
The second is to create a shallow copy of the original document. You can do this using the list () constructor. A shallow copy creates a new object, but references the original object to populate it. Therefore, adding a new object to the original collection li3 will not propagate to li4, but modifying an object in li3 will propagate to li4.
Li3 = [['a'], ['b'], ['c']] li4 = list (li3) li3.append ([4]) print (li4) # = > [['a'], ['b'], ['c']] li3 [0] [0] = ['X'] print (li4) # = > [['X']], ['b'], ['c']
The third is to create a deep copy. This is done through copy.deepcopy (). Now, the two objects are completely independent, and changes to either of them will not affect the other.
Import copyli5 = [['a'], ['b'], ['c']] li6 = copy.deepcopy (li5) li5.append ([4]) li5 [0] [0] = ['X'] print (li6) # = > [['a'], ['b'], ['c']] = >
17. How to join two arrays?
Remember, an array is not a list. Arrays come from Numpy and arithmetic functions, such as linear algebra.
You need to use the connection function of Numpy to do this.
Import numpy as npnpa = np.array ([1, 2, 3]) b = np.array ([4, 5, 5, and 6]) np.concatenate ((a,)) # = > array ([1, 2, 3, 4, 5, 6])
18. Why do you like Python?
Python is very easy to read, and there is a Python way to handle almost everything, which means that it is a simple and straightforward preferred way.
Compare it with Ruby, which usually has many ways to do something, and there is no guide to which is the first choice.
19. Which library of Python do you like best?
When dealing with large amounts of data, nothing is as useful as the pandas library, which makes it easy to manipulate and visualize the data.
20. Naming mutable and immutable objects
Immutable means that the state cannot be modified after creation. For example: int, float, bool, string, and tuple.
Mutable indicates that the state can be modified after creation. Such as lists, dictionaries, and collections.
21. How do I round a number to three decimal places?
Use the round (value,decimal_places) function.
A = 5.12345 round (apome3) # = > 5.123
twenty-two。 How do I split the list?
The slice symbol takes three parameters, list [start:stop:step], where step is the interval between the returned elements.
Print (a [: 2]) # = > [0je 1] print (a [8:]) # = > [8 print (a [2:8]) # = > [2mei 3pm 4pm 5pm 6] print (a [2: 8:2]) # = > [2,4,6]
23. What's the difference between a list and an array?
Note: Python's standard library has an array object, but here it refers specifically to the commonly used Numpy array.
The list exists in the standard library of python, and the array is defined by Numpy.
Lists can be populated with different types of data at each index, and arrays need homogeneous elements.
Operations on the list can add or remove elements from the list, and array functions perform linear algebraic operations.
Arrays take up less memory and have more functions.
Knowledge of arrays is worth writing another article.
24. What is pickling?
Picking is a helper method for serializing and deserializing objects in Python.
In the following example, the dictionary list is serialized and deserialized.
Import pickleobj = [{'id':1,' name':'Stuffy'}, {'id':2,' name':' Fluffy'}] withopen ('file.p',' wb') as f: pickle.dump (obj, f) withopen ('file.p',' rb') as f: loaded_obj = pickle.load (f) print (loaded_obj) # = > [{'id':1,' name':'Stuffy'} {'id': 2,' name': 'Fluffy'}]
25. What's the difference between dictionary and JSON?
Dict is the python data type, which is a collection of indexed but unordered keys and values.
JSON is just a string that follows the specified format and is used to transfer data.
twenty-six。 What ORM is used in Python?
ORM (object-relational mapping) maps the data model (usually in an application) to database tables and simplifies database operations.
SQLAlchemy is usually used in the context of Flask, while Django has its own ORM.
['cased,' baked,'a']
twenty-seven。 How do any () and all () work?
Any accepts a sequence and returns true if any element in the sequence is true.
All returns true only if all elements in the sequence are true.
A = [False, False, False] b = [True, False, False] c = [True, True, True] print (any (a)) print (any (b)) print (any (c)) # = > False # = > True # = > Trueprint (all (a) print (all (b)) print (all (c) # = > False # = > False # = > True
twenty-eight。 Is it faster to find dictionaries or lists?
It takes O (n) time to find a value in a list, because you need to traverse the entire list until a value is found.
It takes O (1) time to find the key in the dictionary because it is a hash table.
If there are many values, the time may vary greatly, so it is usually recommended to use dictionaries to improve speed. But they do have other limitations, such as the need for a unique key.
twenty-nine。 How to return the binary of an integer?
Use the bin () function.
Bin (5) # = > '0b101'
thirty。 How do I remove duplicate elements from the list?
This can be done by converting the list to a collection and then returning to the list.
A = list (set (a)) print (a) # = > [1Jing 2jue 3]
thirty-one。 How do I check if a value exists in the list?
Use in.
'a'in ['a 'False False'] # = > False
thirty-two。 What's the difference between append and extend?
Append adds values to the list, while extend adds values from another list to the list.
A = [1Jing 2jue 3] b = [1JEI 2JEI 3] a.append (6) print (a) # = > [1Med 2Med 3,6] b.extend ([4Med 5]) print (b) # = > [1Med 2Med 3,4Med 5]
thirty-three。 How to take the absolute value of an integer?
This can be done through the abs () function.
Abs (2) # = > 2abs (- 2) # = > 2
thirty-four。 How do I combine two lists into one tuple list?
You can use the zip function to combine lists into a list of tuples. This is not limited to using only two lists. It can also be done with three or more.
A = ['axiao, for,',',
thirty-five。 How to sort dictionaries alphabetically?
The dictionary cannot be sorted because the dictionary has no order, but you can return a sorted list of tuples containing keys and values in the dictionary.
D = {'cantilever 3,' dazzl4, 'breadgaze2jinghuanglu 1} sorted (d.items ()) # = > [(' ajar, 1), ('baked, 2), (' cantilevered, 3), ('dashed, 4)]
thirty-six。 How does one class inherit from another class in Python?
In the following example, Audi inherits from Car. Inheritance brings an instance method of the parent class.
Class Car (): def drive (self): print ('vroom') class Audi (Car): passaudi = Audi () audi.drive ()
thirty-seven。 What is the difference between modules and packaging?
A module is a file (or collection of files) that can be imported together.
Importsklearn
The package is the directory of the module.
From sklearnimport cross_validation
Therefore, packages are modules, but not all modules are packages.
thirty-eight。 How to increment and decrement integers in Python?
You can use +-and-= to increase and decrease.
Value = 5value + = 1 print (value) # = > 6value-= 1 value-= 1 print (value) # = > 4
thirty-nine。 How do I remove all spaces from a string?
The easiest way is to split the string in the space and then reconnect without spaces.
S = 'Astringwithwhitespace' .join (s.split ()) # = >' Astringwithwhitespace'
forty。 Why use enumerate () when iterating over a sequence?
Enumerate () allows you to track the index as you iterate through the sequence. It is more Python than defining and incrementing integers that represent indexes.
Li = [foridx,val in enumerate (li): print (idx,val) # = > 0a # = > 1b # = > 2c # = > 3d # = > 4e
forty-one。 What is the difference between pass, continue, and break?
Pass means doing nothing. It is often used because Python does not allow classes, functions, or if statements to be created without code.
In the following example, if there is no code in I > 3, an error is thrown, so pass is used.
For i in a: if I > 3: pass print (I) # = > 1 # = > 2 # = > 3 # = > 4 # = > 5
Continue continues to the next element and pauses execution of the current element. So for I 3 # = > 4 # = > 5
Break breaks the cycle and the sequence is no longer repeated. Therefore, elements after 3 are not printed.
For i in a: if I = = 3: break print (I) # = > 1 # = > 2
forty-two。 Give an example of a ternary operator.
The ternary operator is a single line if / else statement.
The syntax looks like an if condition else b.
X = 5 y = 10 else'if x > 6 else 'less' # = >' less''greater' if y > 6 else 'less' # = >' greater'
forty-three。 Check to see if the string contains only numbers.
You can use isnumeric ().
'123a'.isnumeric () # = > False'123'.isnumeric () # = > True
forty-four。 Check that the string contains only letters.
You can use isalpha ().
'123a'.isalpha () # = > False'a'.isalpha () # = > True
forty-five。 Check that the string contains only numbers and letters.
You can use isalnum ().
'123abc...'.isalnum () # = > False'123abc'.isalnum () # = > True
forty-six。 Returns a list of keys from the dictionary.
This can be done by passing the dictionary to python's list () constructor list ().
D = {'id':7,' name':'Shiba','color':'brown', 'speed':'very slow'} list (d) # = > [' id', 'name',' color', 'speed']
forty-seven。 How to uppercase and lowercase a string?
You can use the upper () and lower () string methods.
Small_word = 'potatocake' big_word =' FISHCAKE'small_word.upper () # = > 'POTATOCAKE'big_word.lower () # = >' fishcake'
forty-eight。 Convert the following for loop to list parsing.
This for loop.
A = [for i in a 2, 3, 4, 5] a2 = [] a2.append (I + 1) print (a2) # = > [2, 3, 4, 5, 6]
Become:
A3 = [iTun1 for i in a] print (A3) # = > [2, 3, 4, 5, 6]
List parsing is generally considered more Python-like, but still easy to read.
forty-nine。 What is the difference between remove, del, and pop?
Remove () deletes the first matching value.
Li = [li.remove ('b') li # = > ['axiomagol' cedars']
Del deletes elements by index.
Li = ['axiaojiajiaomiajiaoyuyuanzhongd'] del li [0] li # = > [[' bencyclopedia pencils]
Pop () deletes an element by index and returns it.
Li = [li.pop (2) # = > 'c'li # = > [' axiomagol']
fifty。 Give an example of dictionary parsing.
Below, you will create a dictionary with letters as keys and alphabetic indexes as values.
# creating a list of letters import string list (string.ascii_lowercase) alphabet = list (string.ascii_lowercase) # list comprehension d = {val:idx for idx,val in enumerate (alphabet)} d # = > {'aqu: 0, # = > 'baked: 1, # = >' clocked: 2, # = >...
fifty-one。 How do I perform exception handling in Python?
Python provides three words to handle exceptions. Try using "try", "except" and "finally".
The syntax is as follows.
Try: # try to do this except: # if try block fails then do this finally: # always do this
In the following simple example, the try block failed because an integer could not be added to the string. The else block is set to val = 10, and then the finally block is printed.
Try: val = 1 +'A 'except: val = 10 finally: print (' complete') print (val) # = > complete # = > 10
fifty-two。 What's the difference between "func" and "func ()"?
The question is to see if you know that all functions are also objects in python.
Def func (): print ('Im a function') func # = > function _ _ main__.func > func () # = > Im a function
Func represents the object of a function, which can be assigned to a variable or passed to another function. The parenthesized func () calls the function and returns its output.
fifty-three。 Explain how the reduce function works
The principle of thinking alone is difficult to understand, and it takes several times to understand it.
Reduce takes a function and a sequence and iterates over the sequence. In each iteration, the output of the current element and the previous element is passed to the function. Finally, a value is returned.
From functools import reducedefadd_three (XMagol y): return x + yli = [1 reduce (add_three, li) # = > 11
Returns 11, which is the sum of 1 + 2 + 3 + 5.
At this point, I believe you have a deeper understanding of "summing up 53 interview questions and answers about Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.