In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the interview questions about Python". In the daily operation, I believe many people have doubts about the interview questions about Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the questions about Python interview questions. Next, please follow the editor to study!
1. What's the difference between lists and tuples?
I've been asked this question in every python / data science interview I've ever had. Know the answer like the back of your hand.
The list is variable. You can modify it after you create it.
Tuples are immutable. Once you have created a tuple, you cannot change it
The list is in order. They are ordered sequences, usually objects of the same type. That is, all user names sorted by creation date, ["Seth", "Ema", "Eli"]
Tuples have a structure. Each index may have a different data type. That is, the database record in memory, (2, "Ema", "2020mur04Mu16") # id, name, created_at
two。 How to perform string interpolation?
There are three ways to interpolate strings 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))
3. What's the difference between "is" and "="?
Early in my python career, I thought they were the same. Hello, mistake. Therefore, for recording, check identity and = = check for equality.
We will go through 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 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.
4. What is a decorator?
I was asked another question in every interview. It's worth releasing in itself, but if you can write your own examples step by step, you're ready.
The decorator allows you to add functionality to an existing feature by passing it to the decorator, which executes existing functionality and other code.
We will 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_drawn that calls func () and executes some code print (f'{func} is called.) . Then return the defined function
Def logging (func): def log_function_called (): print (f'{func} called.') Func () return log_function_called
Let's write other functions, and we'll eventually add the decorator to (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
See how you can now easily add logs to any function we write just by adding @ logging to it.
5. Explain scope function
Range generates a list of integers that can be used in three ways.
This function takes 1 to 3 parameters. Notice that I wrap each usage in a list derivation so that we 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 = speed car = Car ('red','100mph') car.speed # = >' 100mph'
7. What's the difference between instance, static 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
We will show 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 special properties, which are set to "espresso" by default. Each instance of CoffeeShop is initialized with the property coffee_price. It also has three methods, instance methods, static methods and class methods.
Let's initialize an example of a coffee shop with coffee_price for 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 check the weather with our weather. Big!
Coffee_shop.check_weather () # = > Its sunny
Now, we use the class method to modify the specialty of the coffee shop, and then modify the make_coffee.
Coffee_shop.change_specialty ('drip coffee') # = > Specialty changed to drip coffee coffee_shop.make_coffee () # = > Making drip coffee for $5
Please note that make_coffee used to be used to make espresso, but now it can make filtered coffee!
What's the difference between "func" and "func ()"?
The purpose of this 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
A func is an object that represents a function that can be assigned to a variable or passed to another function. The parenthesized func () calls the function and returns its output.
9. Explain how the Map feature works
Map returns a list of return values by applying a function to each element in the sequence.
Def add_three (x): return x + 3 li = [1Jing 2jue 3] [i for i in map (add_three, li)] # = > [4,5,6]
Above, I added 3 for each element in the list.
10. Explain how the reduce function works
It is difficult to wrap your head around until you use it several times.
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 reduce def add_three (XMagol y): return x + y li = [1 reduce (add_three, li) # = > 11
Returns 11, which is the sum of 1 + 2 + 3 + 5.
11. Explain how the filter feature works
The filter is executed literally. It filters the 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 False li = [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.
12. 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. You'd better only know 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]
13. 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) # = > ['acronym,' baccalaureate'] # = > ['cedar,' bliss,'a']
14. 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.
15. 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]
The output contains a list of content that has been repeated twice [1 ~ 2 ~ 2 ~ 3].
16. What does "self" mean on the class?
The self refers to the 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'
17. 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]
18. What's the difference between a shallow copy and a deep copy?
We will discuss it in the context of mutable objects (lists). For immutable objects, shallowness and depth are not important.
We will introduce three situations.
I) reference the original object. This points the new name li2 to the same location of memory that li1 points to. Therefore, any changes we make to li1 will also occur in li2.
Li1 = [['a'], ['b'], ['c']] li2 = li1 li1.append (['d']) print (li2) # = > [['a'], ['b'], ['c'], ['d']]
Ii) create a shallow copy of the original document. We can do this using the list () constructor. A shallow copy creates a new object, but populates it with a reference to the original object. 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']
Iii) create a deep copy. This is done through copy.deepcopy (). The two objects are now completely independent, and changes made to either of them will not affect the other.
Import copy li5 = [['a'], ['b'], ['c']] li6 = copy.deepcopy (li5) li5.append ([4]) li5 [0] [0] = ['X'] print (li6) # = > [['a'], ['b'], ['c']]
19. What's the difference between a list and an array?
Note: Python's standard library has an array object, but here I'm referring specifically to the commonly used Numpy array.
The list exists in the standard library of python. The array is defined by Numpy.
Lists can be populated with different types of data at each index. An array requires homogeneous elements.
The arithmetic on the list adds or removes elements from the list. The arithmetic operation of the array function of each linear algebra.
The array also uses less memory and has more functionality.
I wrote another article about arrays.
20. How to join two arrays?
Remember, an array is not a list. Arrays come from Numpy and arithmetic functions, such as linear algebra.
We need to use the connection function of Numpy to do this.
Import numpy as np a = np.array ([1, 2, 3]) b = np.array ([4, 5, 5, and 6]) np.concatenate ((a,)) # = > array ([1, 2, 3, 4, 5, 6])
21. What do you like about Python?
Python is very easy to read, and there is a Python way to handle almost everything, which means a concise and straightforward preferred way.
I compare it to Ruby, which usually has many ways to do something, and no guide is the first choice.
twenty-two。 Which library of Python do you like best?
When dealing with large amounts of data, nothing is as useful as a panda, which makes it easy to manipulate and visualize data.
23. Naming mutable and immutable objects
Immutable means that the state cannot be modified after creation. For example: int,float,bool,string and tuple.
The mutable representation state can be modified after creation. Examples are lists, dictionaries and collections.
24. How do you round a number to three decimal places?
Use the round (value,decimal_places) function.
A = 5.12345 round (apome3) # = > 5.123
25. How do you 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]
twenty-six。 What is pickle?
Pickling is the preferred method for serializing and deserializing objects in Python.
In the following example, we serialize and deserialize the dictionary list.
Import pickleobj = [{'id':1,' name':'Stuffy'}, {'id':2,' name':' Fluffy'}] with open ('file.p',' wb') as f: pickle.dump (obj, f) with open ('file.p',' rb') as f: loaded_obj = pickle.load (f) print (loaded_obj) # = > [{'id':1,' name':'Stuffy'} {'id': 2,' name': 'Fluffy'}]
twenty-seven。 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-eight。 What ORM do you use in Python?
ORM (object relational mapping) maps the data model (usually in an application) to database tables and simplifies database transactions.
SQLAlchemy is usually used in the context of Flask, while Django has its own ORM.
twenty-nine。 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 # = > True print (all (a) print (all (b)) print (all (c) # = > False#= > False#= > True
thirty。 Is it faster to find dictionaries or lists?
It takes O (n) time to find a value in a list, because the entire list needs to be traversed until a value is found.
It takes O (1) time to find the key in the dictionary because it is a hash table.
If the value is high, this can cause large jet lag, 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.
thirty-one。 What is the difference between modules and packaging?
A module is a file (or collection of files) that can be imported together.
Import sklearn
The package is the directory of the module.
From sklearn import cross_validation
Therefore, packages are modules, but not all modules are packages.
thirty-two。 How to increment and decrement integers in Python?
You can use +-and-= to increase and decrease.
Value = 5 value + = 1 print (value) # = > 6 value-= 1 value-= 1 print (value) # = > 4
thirty-three。 How to return the binary of an integer?
Use the bin () function.
Bin (5) # = > '0b101'
thirty-four。 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-five。 How do I check if a value exists in the list?
For.
'a' in ['a 'False'] # = > True'a'in [1m 2pm 3] # = > False
thirty-six。 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-seven。 How to take the absolute value of an integer?
This can be done through the abs () function.
Abs (2) # = > 2 abs (- 2) # = > 2
thirty-eight。 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-nine。 How to sort dictionaries alphabetically?
You cannot "sort" dictionaries because they are not in order, but you can return a sorted list of tuples containing keys and values in the dictionary.
D = {'cantilevered sorted 3,' donglu 4, 'baked vig 2,' afrol1} sorted (BBG ()) # = > [('a', 1), ('baked, 2), (' cantilevered, 3), ('dumped, 4)]
forty。 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): pass audi = Audi () audi.drive ()
forty-one。 How do I remove all spaces from a string?
The easier way is to split the string in the space and then reconnect without spaces.
S = 'Astringwithwhitespace' .join (s.split ()) # = >' Astringwithwhitespace'
forty-two。 Why use enumerate () when iterating over a sequence?
Enumerate () allows you to track the index as you iterate over the sequence. It is more Python than defining and incrementing integers that represent indexes.
Li = [for idx,val in enumerate (li): print (idx,val) # = > 0a # = > 1b # = > 2c # = > 3d # = > 4e
43. What's the difference between passforce continue and break?
Passing means doing nothing. We usually use it because Python does not allow classes, functions, or if statements to be created without code in it.
In the following example, if there is no code in I > 3, an error is thrown, so we use pass.
For i in a: if I > 3: pass print (I) # = > 1 # = > 2 # = > 3 # = > 4 # = > 5
Continues to the next element and pauses the 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-four。 Convert the following for loop to list derivation.
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 comprehension is generally considered to be more Python, but still easy to read.
forty-five。 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 'greater' if x > 6 else' less' # = > 'less'' greater' if y > 6 else 'less' # = >' greater'
forty-six。 Check to see if the string contains only numbers.
You can use isnumeric ().
'123a'.isnumeric () # = > False '123'.isnumeric () # = > True
forty-seven。 Check that the string contains only letters.
You can use isalpha ().
'123a'.isalpha () # = > False 'a'.isalpha () # = > True
forty-eight。 Check that the string contains only numbers and letters.
You can use isalnum ().
'123abc...'.isalnum () # = > False '123abc'.isalnum () # = > True
forty-nine。 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']
fifty。 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'
fifty-one。 What's 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 # = > ['axiomanaginomagenical]
fifty-two。 Give an example of dictionary understanding.
Below, we 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 comprehensiond = {val:idx for idx,val in enumerate (alphabet)} d # = > {'aqu: 0, # = > 'baked: 1, # = >' clocked: 2, # = >...
fifty-three。 How do I perform exception handling in Python?
Python provides three words to handle exceptions. Try using "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 we could not add an integer 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 this is the end of the study on "what are the interview questions about Python". I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.