Ex 22: Function Behavior Analyzer
Problem
We're building a tool to demonstrate different programming paradigms in Python. Implement a suite of functions that showcase purity, recursion, and higher-order patterns.
Rules
- Pure Function: Must not modify external state or rely on it.
- Impure Function: Use a global variable and update it.
- Recursion: Implement a factorial function with a clear base case.
- Lambda & Map: Use a lambda within
map()to transform a list of numbers.
Boilerplate
Copy below code and paste to our IDE for head start.
# 1. Pure Function: returns a + b without side effects
def pure_add(a: int, b: int) -> int:
pass
# 2. Impure Function: increments global 'counter'
counter = 0
def impure_increment() -> int:
pass
# 3. Recursive Function: calculates factorial of n
def factorial_recursive(n: int) -> int:
pass
# 4. Lambda with map(): returns a list of squares
def square_list(nums: list[int]) -> list[int]:
pass
# Tests
print(pure_add(10, 5))
print(impure_increment())
print(factorial_recursive(5))
print(square_list([1, 2, 3, 4]))
Expected output
15
1
120
[1, 4, 9, 16]
Solution & Reasoning
Only view the solution after trying our best
def pure_add(a, b):
return a + b
counter: int = 0
def impure_increment():
global counter
counter += 1
return counter
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
def square_list(nums: list[int]) -> list[int]:
return list(map(lambda num: num**2, nums))
Details
- Pure Add: By only using local variables
aandb, this function remains predictable and side-effect free. - Impure Increment: The
globalkeyword allows modification of variables outside the function's scope, making it "impure." - Factorial: Recursion breaks the problem down. The base case
n == 0is essential to preventRecursionError. - Square List:
map()is a higher-order function that applies the anonymouslambdato every element, creating a memory-efficient iterator that we convert back to alist.