Scenario-Based Python Interview Questions and Answers (2025)
Scenario-Based Python Interview Questions and Answers (2025)
1. Scenario: You are given a list of integers. Write a Python function to find the two numbers that sum up to a target value.
Question:
You are given a list of integers, and a target value. Write a Python function that returns the indices of two numbers such that they add up to the target value.
Solution:
def two_sum(nums, target):
seen = {}
for i, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], i]
seen[num] = i
return None
# Example usage
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target)) # Output: [0, 1]
Explanation:
This solution uses a hash map (seen
) to store the previously visited numbers and their indices. This allows the algorithm to find the complement of the current number in constant time.
2. Scenario: You need to calculate the factorial of a number in Python, but the number is too large. How would you approach this using Python?
Question:
Write a Python function to calculate the factorial of a large number efficiently.
Solution:
import math
def large_factorial(n):
return math.factorial(n)
# Example usage
print(large_factorial(100)) # Output: 9.33262154439441e+157
Explanation:
The built-in math.factorial
function efficiently handles large numbers in Python by using an optimized algorithm and arbitrary-precision arithmetic.
3. Scenario: Given a string, write a Python function to determine if it is a palindrome.
Question:
Write a Python function that checks if a given string is a palindrome (reads the same forward and backward).
Solution:
def is_palindrome(s):
return s == s[::-1]
# Example usage
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
Explanation:
The function uses Python's slicing feature to reverse the string and compares it with the original string.
4. Scenario: You are tasked with reading a large CSV file and calculating the sum of all values in a specific column.
Question:
How would you write Python code to read a large CSV file and calculate the sum of a specific column?
Solution:
import csv
def sum_column(file_path, column_index):
total = 0
with open(file_path, mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
total += float(row[column_index])
return total
# Example usage
print(sum_column('large_file.csv', 2)) # Sum of column at index 2
Explanation:
This code reads the CSV file row by row, skipping the header, and sums the values in a specific column using float()
to ensure proper type conversion.
5. Scenario: You need to write a Python function that finds the longest common prefix in a list of strings.
Question:
Given a list of strings, write a Python function that finds the longest common prefix among them.
Solution:
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for string in strs[1:]:
while not string.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
# Example usage
print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"
Explanation:
The algorithm starts with the first string as the prefix and iteratively shortens it until it matches the start of all strings in the list.
6. Scenario: You need to write a Python function to sort a list of dictionaries based on a key.
Question:
Write a Python function that sorts a list of dictionaries based on a specific key.
Solution:
def sort_dicts_by_key(dict_list, key):
return sorted(dict_list, key=lambda x: x[key])
# Example usage
data = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
print(sort_dicts_by_key(data, 'age'))
# Output: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
Explanation:
The sorted()
function sorts the list of dictionaries by the value of the specified key using a lambda function.
Comments
Post a Comment