Here are 30 intermediate Python questions and answers that can be useful for an interview:
- User
Here are 30 intermediate Python questions and answers that can be useful for an interview:
- Assistant
Absolutely, preparing a comprehensive set of intermediate Python interview questions can be immensely beneficial. Here are 30 questions along with their answers that cover various concepts and features of Python. These questions are designed to evaluate a candidate's grasp of Python beyond the basics.
1. What are Python decorators, and how would you use one?
A Python decorator is a specific change that we make in Python syntax to alter functions easily. A decorator is a callable that takes a callable as an input and returns another callable. You can use a decorator to wrap a function, modifying its behavior.
def my_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @my_decorator def say_hello(): print("Hello!")2. What is the difference between lists and tuples in Python?
The key difference is that lists are mutable, whereas tuples are immutable. This means that you can change, add, or remove elements in a list, but you cannot do so in a tuple.
3. How does Python manage memory?
Python uses a private heap space to manage memory. All Python objects and data structures are located in a private heap. The Python memory manager controls this allocation, including the management of a private heap space. Additionally, Python has an inbuilt garbage collector to recycle unused memory.
4. How can you achieve multithreading in Python?
Python provides a
threadingmodule to manage threads. You can create threads by directly using theThreadclass or by extending it.import threading def print_numbers(): for i in range(10): print(i) thread = threading.Thread(target=print_numbers) thread.start()5. What are *args and **kwargs, and when would you use them?
*argsallows you to pass a variable number of arguments to a function.**kwargsallows you to pass a variable number of keyword arguments to a function.
These are useful when you are unsure of the number of arguments that will be passed to your functions.
6. Explain the difference between deep and shallow copy.
- A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
7. What is PEP 8?
PEP 8 is the style guide for Python code. It was written to improve the readability and consistency of Python code.
8. What are generators in Python?
Generators are a way of creating iterators in a very clean and efficient way. A generator is a function that returns an iterator. It generates values using the
yieldstatement.9. What is list comprehension and give an example?
List comprehension provides a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable.
Example:
numbers = [1, 2, 3, 4] squares = [n**2 for n in numbers]10. Explain the
withstatement in Python.The
withstatement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. For example, it can be used to open a file, where it ensures the file is properly closed after its suite finishes, even if an exception is raised.with open('file.txt', 'r') as file: content = file.read()11. What is the difference between
==andis?==is used for equality comparison, meaning it checks if the values of two operands are equal.ischecks for identity, meaning it checks whether both the operands refer to the same object or not.
12. How do you implement a Singleton pattern in Python?
A Singleton pattern ensures a class has only one instance and provides a global point of access to it. You can implement it using a class variable that keeps track of the instance.
class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance13. What are the key features of Python?
- Easy to read, learn, and write
- Interpreted language
- Dynamically typed
- Vast standard library
- Supports multiple programming paradigms
14. How can you share global variables across modules?
To share global variables across modules in a single program, you can create a special module (often named config or settings). Import the config module in all modules of your application. The module then becomes accessible as a global variable across modules.
15. Explain the concept of namespace in Python.
A namespace in Python is a naming system used to ensure that names are unique and can be reused. Functions, modules, and packages all have their own namespaces, known as local, global, and built-in namespaces, respectively.
16. What is slicing?
Slicing is a method for extracting a part of a sequence (string, tuple, list) using its indices. Python uses a
:operator to achieve slicing.Example:
my_list = [1, 2, 3, 4, 5] slice = my_list[1:4] # This will extract items 2 through 4.17. What are lambda functions?
Lambda functions are small anonymous functions defined with the lambda keyword. They can have any number of arguments but can only have one expression.
Example:
square = lambda x: x ** 2 print(square(5)) # Output: 2518. How do you debug a Python program?
You can use the Python
pdbmodule (Python Debugger) to debug a program. Thepdbcan be used from the command line withpython -m pdb myscript.pyor can be incorporated within the code usingimport pdb; pdb.set_trace().19. What is Python's Global Interpreter Lock (GIL)?
The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This means that in a multi-threaded Python program, only one thread can execute Python code at a time.
20. What are Python's dictionaries?
A dictionary in Python is an unordered collection of data values used to store data values like a map. Unlike other data types that hold only a single value as an element, dictionaries hold key:value pairs.
Example:
my_dict = {'name': 'John', 'age': 30}21. What is a virtual environment and why would you use one?
A virtual environment in Python is a self-contained directory that contains a Python installation for a particular version of Python, plus a number of additional packages. You use a virtual environment to manage dependencies for different projects and to ensure consistency across development and production environments.
22. What does the
if __name__ == "__main__":do?This condition checks whether the module is being run directly by the interpreter or imported by another module. If the condition evaluates to True, the code block beneath it runs. This is often used to run code that should only be executed when the script is executed directly, not when it's imported as a module.
23. How does Python handle the inheritance of private and protected members in a class?
In Python, no member is truly private. Conventionally, a member that should not be accessed directly is prefixed with an underscore
_, signaling it should be treated as protected. Members prefixed with double underscore__are name-mangled to prevent easy access from outside the class but are still accessible with _ClassName__memberName.24. What is package in Python?
A package in Python is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on. Packages allow for a hierarchical structuring of the module namespace using dot notation.
25. Explain Python's error handling with
try-exceptblock.Python uses
try-exceptblocks to catch and handle exceptions. Code that might raise an exception is placed in thetryblock, and handling of the exception is implemented in theexceptblock.try: print(1 / 0) except ZeroDivisionError: print("You cannot divide by zero!")26. What is the Python walrus operator, and how is it used?
The walrus operator
:=allows you to assign values to variables as part of expression. This can make the code more concise by avoiding separate lines for assignment and checking conditions.Example:
if (n := len(a)) > 10: print(f"List is too long ({n} elements)")27. How can you convert a string into a datetime object in Python?
You can use the
datetimemodule in Python along with thestrptime()method to convert a string into a datetime object.from datetime import datetime datetime_str = '09/19/18 13:55:26' datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S') print(datetime_object)28. How can you remove duplicates from a list in Python?
You can remove duplicates by converting a list to a set, which automatically removes all duplicate entries, and then back to a list if needed.
my_list = [1, 2, 2, 3, 4, 4, 5] my_list = list(set(my_list)) print(my_list) # Output: [1, 2, 3, 4, 5]29. What are the differences between Django and Flask?
- Django is a full-stack web framework for Python, whereas Flask is a lightweight, micro web framework.
- Django is more suitable for larger applications, providing more out-of-the-box solutions. Flask gives more control and is more suitable for smaller projects or microservices.
30. How can you improve the performance of a Python application?
- Use built-in data types and libraries wherever possible.
- Leverage multi-threading and multiprocessing.
- Use efficient algorithms and data structures.
- Optimize your code by using a profiler to find bottlenecks.
- Avoid global variables or use them judiciously.
- Use lazy loading and caching techniques.
- User
write 20 more questions
- Assistant
Certainly! Here are 20 more intermediate-level Python interview questions to help deepen your understanding and preparation:
31. What is the GIL (Global Interpreter Lock) and how does it affect Python concurrency?
The GIL is a mutex that prevents multiple native threads from executing Python bytecodes at once. This means that even in a multi-threaded script, only one thread can execute Python code at a time. It's a feature necessary because CPython's memory management is not thread-safe. The GIL can be a performance bottleneck for CPU-bound multi-threaded programs.
32. Explain the difference between the
map,filter, andreducefunctions in Python.map(function, iterable, ...): applies a given function to all items in an input list.filter(function, iterable): constructs an iterator from elements of an iterable for which a function returns true.reduce(function, sequence[, initial]): applies a rolling computation to sequential pairs of values in a list.
33. How do you make a Python script executable on Unix?
To make a script executable on Unix, add a shebang at the top of the script (e.g.,
#!/usr/bin/env python3), and then make the script executable with the chmod command (e.g.,chmod +x script.py).34. What is Monkey Patching in Python?
Monkey patching is a term used to describe the dynamic modifications of a class or module at runtime, intended to extend or modify its behavior for specific purposes.
35. How would you set up and use a virtual environment in Python?
You use the
venvmodule available in Python 3 to create a virtual environment. Usepython3 -m venv myvenvto create a new virtual environment. You can activate it usingsource myvenv/bin/activateon Unix ormyvenv\Scripts\activateon Windows.36. How can you make a Python code faster?
- Optimize algorithmic efficiency.
- Use built-in functions and libraries.
- Implement generators and comprehensions.
- Use arrays if elements are of the same data type.
- Profile the code to find bottlenecks.
37. What is
__init__.pyused for in Python?The
__init__.pyfile is used to signal to Python that a directory contains a package. It can be left empty but is often used to perform initialization tasks needed for the package.38. Explain the use of the
enumeratefunction in Python.enumerate()adds a counter to an iterable and returns it in a form of enumerating object. This can be directly used in for loops or be converted into a list of tuples usinglist()method.39. What are metaclasses in Python?
Metaclasses in Python are classes of classes that define how a class behaves. A class is an instance of a metaclass. You can use metaclasses to create classes according to specific patterns.
40. How does Python handle immutable objects?
Python handles immutable objects by storing them in memory only once. This is efficient for memory and performance since an immutable object does not change and can be shared or reused.
41. What is the difference between
@classmethod,@staticmethod, and@propertyin Python?@classmethod: defines a class method that takesclsas the first parameter while calling.@staticmethod: defines a method that doesn’t operate on an instance and doesn’t modify class state.@property: turns the method into a "getter" for a readonly attribute with the same name.
42. How can you use a MySQL database with Python?
You can use the
mysql-connector-pythonpackage to connect Python applications with MySQL databases. After installing the package with pip, you can establish a connection, execute SQL queries, and retrieve data.43. What is the significance of Python's
passstatement?passis a null statement in Python. It results in no operation (NOP). It is significant as a placeholder in compound statements where there is a syntactical requirement for at least one statement but where no action is required.44. How do you ensure proper closure of files/resources in Python?
You use the
withstatement in Python, known as a context manager. It ensures proper acquisition and release of resources, making the code cleaner and more readable.45. What are Python iterators, and how do you implement one?
Iterators in Python are objects that can be iterated over in a loop. You can implement an iterator using Python classes with
__iter__()and__next__()methods.46. Explain the usage of "else" clause in loops in Python.
In Python, the
elseclause in a loop executes after the loop finishes its iteration normally, without hitting abreakstatement. It's a unique feature of Python, not found in many other programming languages.47. What are Python wheels?
Wheels are the new standard of Python distribution and are intended to replace eggs. They are a packaging format for Python libraries and applications that allows for faster installations and avoids the necessity for compilation.
48. How do you manage package versions in a Python project?
You manage package versions in Python projects using a
requirements.txtfile or a Pipfile (when using pipenv). These files list all dependencies with their versions, ensuring consistency across environments.49. What is Type Hinting in Python?
Type hinting is a feature in Python that allows you to specify the expected data types of function arguments and return values. While Python is dynamically typed, type hints can help with code readability and can be used by static type checkers.
50. Explain duck typing in Python.
Duck typing in Python refers to the language's approach of not caring about the type of a class but rather its methods or behavior. If an object quacks like a duck (implements required methods), then it's treated as a duck. This enables polymorphism without requiring inheritance.
- User
write 10 coding questions and answers at intermediate level
- Assistant
Here are 10 intermediate Python coding interview questions along with their answers. These questions cover various aspects of Python, from data structures and algorithms to Python-specific features and design patterns.
1. Find All Duplicates in an Array
Given an array of integers, some elements appear twice and others appear once. Find all the elements that appear twice in this array.
Question:
def findDuplicates(nums): # Your code here passAnswer:
def findDuplicates(nums): duplicates = [] for num in nums: if nums[abs(num) - 1] < 0: duplicates.append(abs(num)) else: nums[abs(num) - 1] *= -1 return duplicates # Example usage print(findDuplicates([4,3,2,7,8,2,3,1])) # Output: [2, 3]2. Encode and Decode Strings
Design an algorithm to encode a list of strings to a single string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Question:
class Codec: def encode(self, strs): """Encodes a list of strings to a single string.""" def decode(self, s): """Decodes a single string to a list of strings."""Answer:
class Codec: def encode(self, strs): return ''.join('%d:' % len(s) + s for s in strs) def decode(self, s): strs = [] i = 0 while i < len(s): j = s.find(':', i) i = j + 1 + int(s[i:j]) strs.append(s[j+1:i]) return strs # Example usage codec = Codec() encoded = codec.encode(["hello", "world"]) print(encoded) # Output: "5:hello5:world" decoded = codec.decode(encoded) print(decoded) # Output: ["hello", "world"]3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Question:
def lengthOfLongestSubstring(s): # Your code here passAnswer:
def lengthOfLongestSubstring(s): charMap = {} left = 0 maxLength = 0 for right in range(len(s)): if s[right] in charMap: left = max(left, charMap[s[right]] + 1) charMap[s[right]] = right maxLength = max(maxLength, right - left + 1) return maxLength # Example usage print(lengthOfLongestSubstring("abcabcbb")) # Output: 34. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Question:
def merge(intervals): # Your code here passAnswer:
def merge(intervals): intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: merged[-1][1] = max(merged[-1][1], interval[1]) return merged # Example usage print(merge([[1,3],[2,6],[8,10],[15,18]])) # Output: [[1,6],[8,10],[15,18]]5. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Question:
def isValid(s): # Your code here passAnswer:
def isValid(s): stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping: top_element = stack.pop() if stack else '#' if mapping[char] != top_element: return False else: stack.append(char) return not stack # Example usage print(isValid("()[]{}")) # Output: True6. Product of Array Except Self
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Question:
def productExceptSelf(nums): # Your code here passAnswer:
def productExceptSelf(nums): length = len(nums) answer = [1]*length left = 1 for i in range(1, length): left *= nums[i-1] answer[i] *= left right = 1 for i in reversed(range(length-1)): right *= nums[i+1] answer[i] *= right return answer # Example usage print(productExceptSelf([1,2,3,4])) # Output: [24, 12, 8, 6]7. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
Question:
def topKFrequent(nums, k): # Your code here passAnswer:
from collections import Counter import heapq def topKFrequent(nums, k): count = Counter(nums) return heapq.nlargest(k, count.keys(), key=count.get) # Example usage print(topKFrequent([1,1,1,2,2,3], 2)) # Output: [1, 2]8. Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Question:
def findDuplicate(nums): # Your code here passAnswer:
def findDuplicate(nums): slow = nums[0] fast = nums[0] slow = nums[slow] fast = nums[nums[fast]] while slow != fast: slow = nums[slow] fast = nums[nums[fast]] fast = nums[0] while slow != fast: slow = nums[slow] fast = nums[fast] return slow # Example usage print(findDuplicate([1,3,4,2,2])) # Output: 29. Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Question:
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def inorderTraversal(root): # Your code here passAnswer:
def inorderTraversal(root): res = [] stack = [] current = root while current or stack: while current: stack.append(current) current = current.left current = stack.pop() res.append(current.val) current = current.right return res # Example usage: # Construct the tree: # 1 # \ # 2 # / # 3 root = TreeNode(1) root.right = TreeNode(2) root.right.left = TreeNode(3) print(inorderTraversal(root)) # Output: [1, 3, 2]10. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Question:
def groupAnagrams(strs): # Your code here passAnswer:
def groupAnagrams(strs): res = {} for s in strs: sortedStr = ''.join(sorted(s)) if sortedStr in res: res[sortedStr].append(s) else: res[sortedStr] = [s] return list(res.values()) # Example usage print(groupAnagrams(["eat","tea","tan","ate","nat","bat"])) # Output: [["bat"],["nat","tan"],["ate","eat","tea"]]These intermediate-level coding questions and their solutions should provide a robust practice regime for honing your problem-solving skills with Python.
- User
write 10 coding questions and answers at moderate level
- Assistant
Certainly! Below are 10 moderate-level Python coding problems along with their solutions. These questions will challenge your understanding of algorithms, data structures, and Python-specific features.
1. Rotate Image
You have to rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Question:
def rotate(matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """Answer:
def rotate(matrix): n = len(matrix) for i in range(n // 2): for j in range(i, n - i - 1): temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] matrix[j][n - i - 1] = temp2. Spiral Matrix
Given an
m x nmatrix, return all elements of the matrix in spiral order.Question:
def spiralOrder(matrix): """ :type matrix: List[List[int]] :rtype: List[int] """Answer:
def spiralOrder(matrix): result = [] while matrix: result += matrix.pop(0) matrix = list(zip(*matrix))[::-1] return result3. Set Matrix Zeroes
Given an
m x nmatrix. If an element is 0, set its entire row and column to 0. You must do it in place.Question:
def setZeroes(matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """Answer:
def setZeroes(matrix): rows, cols = len(matrix), len(matrix[0]) row_zero = False for r in range(rows): for c in range(cols): if matrix[r][c] == 0: matrix[0][c] = 0 if r == 0: row_zero = True else: matrix[r][0] = 0 for r in range(1, rows): for c in range(1, cols): if matrix[0][c] == 0 or matrix[r][0] == 0: matrix[r][c] = 0 if matrix[0][0] == 0: for r in range(rows): matrix[r][0] = 0 if row_zero: for c in range(cols): matrix[0][c] = 04. Word Search
Given an
m x ngrid of characters board and a string word, returntrueif word exists in the grid.Question:
def exist(board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """Answer:
def exist(board, word): if not board: return False for i in range(len(board)): for j in range(len(board[0])): if dfs(board, i, j, word): return True return False def dfs(board, i, j, word): if len(word) == 0: return True if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or word[0] != board[i][j]: return False temp = board[i][j] board[i][j] = "#" result = dfs(board, i+1, j, word[1:]) or dfs(board, i-1, j, word[1:]) \ or dfs(board, i, j+1, word[1:]) or dfs(board, i, j-1, word[1:]) board[i][j] = temp return result5. Combination Sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target.
Question:
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """Answer:
def combinationSum(candidates, target): def backtrack(remain, combo, start): if remain == 0: results.append(list(combo)) return elif remain < 0: return for i in range(start, len(candidates)): combo.append(candidates[i]) backtrack(remain - candidates[i], combo, i) combo.pop() results = [] backtrack(target, [], 0) return results6. Jump Game
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.
Question:
def canJump(nums): """ :type nums: List[int] :rtype: bool """Answer:
def canJump(nums): goal = len(nums) - 1 for i in range(len(nums) - 1, -1, -1): if i + nums[i] >= goal: goal = i return goal == 07. Unique Paths
A robot is located at the top-left corner of a
m x ngrid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid. How many possible unique paths are there?Question:
def uniquePaths(m, n): """ :type m: int :type n: int :rtype: int """Answer:
def uniquePaths(m, n): dp = [1] * n for i in range(1, m): for j in range(1, n): dp[j] += dp[j - 1] return dp[-1]8. Decode Ways
A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. Given a non-empty string containing only digits, determine the total number of ways to decode it.
Question:
def numDecodings(s): """ :type s: str :rtype: int """Answer:
def numDecodings(s): if not s or s[0] == '0': return 0 dp = [0] * (len(s) + 1) dp[0], dp[1] = 1, 1 for i in range(2, len(s) + 1): if 0 < int(s[i-1:i]) <= 9: dp[i] += dp[i-1] if 10 <= int(s[i-2:i]) <= 26: dp[i] += dp[i-2] return dp[-1]9. Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product and return the product.
Question:
def maxProduct(nums): """ :type nums: List[int] :rtype: int """Answer:
def maxProduct(nums): if not nums: return 0 max_prod, min_prod, result = nums[0], nums[0], nums[0] for i in range(1, len(nums)): if nums[i] < 0: max_prod, min_prod = min_prod, max_prod max_prod = max(nums[i], max_prod * nums[i]) min_prod = min(nums[i], min_prod * nums[i]) result = max(result, max_prod) return result10. Longest Consecutive Sequence
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time.
Question:
def longestConsecutive(nums): """ :type nums: List[int] :rtype: int """Answer:
def longestConsecutive(nums): num_set = set(nums) longest_streak = 0 for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streakThese moderate-level problems cover a variety of topics and will help sharpen your problem-solving skills and your ability to utilize Python's features effectively.