Home Uncategorized Python Functions, Modules, Packages, Built-in Libraries: 20 Coding...
Uncategorized

Python Functions, Modules, Packages, Built-in Libraries: 20 Coding Interview Questions

Python functions and modules enable code reuse, organization, and abstraction. Decorators, closures, *args/**kwargs, and modular design patterns appear in every professional Python codebase and interview.

Functions: From Basics to Advanced Design

Function Definition and Scope: Functions encapsulate logic, enable reuse. def keyword defines function, return statement exits with value. Local scope: variables inside function only accessible there. Global scope: module-level variables accessible everywhere. Nonlocal keyword: nested functions access parent scope. Understanding scope prevents variable shadowing bugs.

def greet(name):
message = f”Hello, {name}!”
return message
result = greet(“Alice”)
global_var = 10
def modify_global():
global global_var
global_var = 20

Default Arguments and Type Hints: Default arguments provide fallback values. Immutable defaults (None, int, str) safe; mutable defaults (list, dict) shared across calls. Type hints document expected types, enable IDE autocomplete. Annotations don’t enforce types but enable type checkers (mypy) to catch errors before runtime.

def calculate(x: int, y: int = 10) -> int:
return x + y
from typing import List, Dict, Optional
def process(items: List[str], config: Optional[Dict] = None) -> bool:
if config is None:
config = {}
return len(items) > 0

*args and **kwargs: *args captures variable positional arguments as tuple, **kwargs captures keyword arguments as dict. Essential for flexible APIs. *args enables functions accepting 0 to n arguments. **kwargs enables keyword-only parameters. Combined enables powerful, extensible function signatures.

def sum_all(*numbers):
return sum(numbers)
def print_config(**settings):
for key, val in settings.items():
print(f”{key}={val}”)
def flexible(a, *args, b=10, **kwargs):
pass

Decorators and Closures: Closures: nested functions capturing parent scope variables. Decorators: functions wrapping other functions, modifying behavior. Decorator syntax @decorator applied above function definition. functools.wraps preserves original function metadata. Essential for cross-cutting concerns (logging, timing, caching, authentication).

def outer(x):
def inner(y):
return x + y
return inner
add_5 = outer(5)
print(add_5(3))
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f”Took {time.time() – start:.2f}s”)
return result
return wrapper
@timer
def slow_function():
pass

Modules and Packages: Modules: .py files containing Python code. Packages: directories with __init__.py enabling imports. import statement loads module, from…import imports specific items. __name__ == ‘__main__’ enables scripts executable directly or importable. sys.path determines import search locations. Relative imports (…) navigate package structure. Understanding module system enables organized, maintainable codebases.

import os
from datetime import datetime
import sys
from collections import Counter, defaultdict
if __name__ == ‘__main__’:
print(“Running as script”)
from . import sibling_module
from ..parent import parent_module

Built-in Libraries Essentials: collections: Counter (frequencies), defaultdict (default values), namedtuple (lightweight classes), deque (efficient queues). itertools: combinations, permutations, chain (lazy evaluation). functools: reduce, partial (function currying), lru_cache (memoization). These libraries solve common problems efficiently, avoiding reinventing wheels.

from collections import Counter
freq = Counter(“hello”)
from itertools import combinations
pairs = list(combinations([1, 2, 3], 2))
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)

5 Complete Solved Coding Problems

Question 1: Implement Retry Decorator with Arguments

Create decorator accepting max_retries parameter. Logs failures, retries with exponential backoff. Returns result on success.

from functools import wraps
import time
def retry(max_attempts=3, backoff=2):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempt = 0
while attempt < max_attempts: try: return func(*args, **kwargs) except Exception as e: attempt += 1 if attempt >= max_attempts:
raise
wait = backoff ** attempt
print(f”Attempt {attempt} failed, retrying in {wait}s”)
time.sleep(wait)
return wrapper
return decorator
@retry(max_attempts=3, backoff=2)
def unreliable_api():
import random
if random.random() < 0.7: raise ConnectionError("Failed") return "Success"

Explanation: Decorator factory returns decorator, enabling parameters. Nested wrapper captures parameters in closure. Exception handling with retry loop. Exponential backoff prevents overwhelming API. functools.wraps preserves metadata.

Google – Senior SWE

Question 2: Counter for Substring Frequencies

Find all unique substrings of length k. Count frequencies using Counter. Handle edge cases efficiently.

from collections import Counter
def substring_frequencies(text, k):
substrings = [text[i:i+k] for i in range(len(text) – k + 1)]
return Counter(substrings)
result = substring_frequencies(“abcabc”, 2)
print(result)

Explanation: List comprehension generates all k-length substrings. Counter counts occurrences automatically. Most common method: result.most_common(n) returns top n.

Meta – Software Engineer

Question 3: Curry Function with functools.partial

Create curried function multiplying three numbers. Use partial to bind arguments progressively.

from functools import partial
def multiply(x, y, z):
return x * y * z
multiply_by_2 = partial(multiply, 2)
result = multiply_by_2(3, 4)
multiply_by_2_3 = partial(multiply_by_2, 3)
result2 = multiply_by_2_3(4)

Explanation: partial creates new function with fixed arguments. Enables function currying without lambda. Useful for callbacks, map/filter operations, creating specialized functions from general ones.

Amazon – Senior SWE

Question 4: Map/Filter/Reduce for Data Processing

Process list of dicts (users with ages). Filter adults (18+), map to names, reduce to count. One-liner approach.

from functools import reduce
users = [{“name”: “Alice”, “age”: 25}, {“name”: “Bob”, “age”: 17}, {“name”: “Charlie”, “age”: 30}]
adult_names = list(map(lambda u: u[“name”], filter(lambda u: u[“age”] >= 18, users)))
print(adult_names)
count = reduce(lambda acc, x: acc + 1, adult_names, 0)
print(count)

Explanation: filter returns iterator of matching items. map transforms items. reduce accumulates to single value. Functional approach avoids explicit loops, but list comprehension often more readable.

Apple – Software Engineer

Question 5: Complex Module Import with Relative Imports

Build package structure with nested modules. Use relative imports to cross-reference. Demonstrate __init__.py usage.

# mypackage/__init__.py
from .utils import helper
from .models import User
__all__ = [“helper”, “User”]
# mypackage/utils.py
def helper():
return “Helper function”
# mypackage/models.py
from . import utils
class User:
def __init__(self, name):
self.name = name
# Usage
from mypackage import User, helper
user = User(“Alice”)
print(helper())

Explanation: __init__.py makes directory a package. __all__ defines public API. Relative imports (.) reference current package. Enables namespace organization, prevents naming conflicts, scales to large projects.

Microsoft – Senior SWE

15 Practice Questions (Test Your Understanding)

Question 6: Write memoization decorator using lru_cache. Calculate Fibonacci fib(40) noting performance improvement vs naive recursion.

Question 7: Create context manager (with statement support) for file handling. Implement __enter__ and __exit__ methods for resource management.

Question 8: Build class with property decorators (getter/setter). Validate age when set. Use @property and @age.setter.

Question 9: Implement generator function yielding Fibonacci numbers infinitely. Use next() to get values one-by-one.

Question 10: Create defaultdict for grouping list of tuples (key, value). Extract values by key with automatic list creation.

Question 11: Write function composition decorator that chains functions. Execute f(g(h(x))) elegantly.

Question 12: Implement namedtuple for Point(x, y). Create 10 random points, find closest pair using distance calculation.

Question 13: Build decorator that converts function return value to JSON string. Handles complex objects via custom encoder.

Question 14: Create module-level logger using logging module. Log different severity levels (debug, info, warning, error).

Question 15: Implement itertools.combinations for generating all pairs from list. Compare with nested loop approach.

Question 16: Write function using itertools.chain to flatten list of lists. Compare performance vs nested comprehension.

Question 17: Create Counter-based voting system. Find winner (most votes) and handle ties systematically.

Question 18: Build dictionary using defaultdict(list). Append values to auto-created lists without key existence checks.

Question 19: Implement functools.reduce for computing product of list. Handle empty list edge case.

Question 20: Write import hook that intercepts module imports. Log all imported modules during script execution.

Master Python Functions & Modules

Get our comprehensive Data Analytics: Ace All The Interview Concepts course.

Scroll to Top