Day 15: Python's functools Module - Power of Function Utilities
Sarasa Jyothsna Kamireddi
Aspiring Python Developer | Machine Learning Enthusiast | Experienced in Reliability Engineering
The functools module provides powerful tools to optimize and enhance functions, making our code more efficient and readable
1?? lru_cache() - Speed Up Function Calls with Caching
If a function performs expensive calculations, caching results can significantly improve performance
from functools import lru_cache
@lru_cache(maxsize=3) # Stores up to 3 previous results
def fib(n):
if n<=1:
return n
return fib(n-1) + fib(n-2)
print(fib(10)) # Faster due to caching!
?? Best for: Avoiding redundant calculations, optimizing recursive functions
2?? reduce() - Reduce a List to a Single Value
Applies a function cumulatively to elements in an iterable
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x*y, nums) # 1*2*3*4 = 24
print(result)
?? Best for: Aggregating values (sum, product, max, etc.)
3?? partial() - Create Preconfigured Functions
Fixes certain arguments in a function, creating a new specialized function
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2) # Predefine exponent =2
print(square(4)) # 16
?? Best for: Preconfiguring function arguments for reuse
4?? cmp_to_key() - Custom Sorting with Comparison Functions
Converts old-style comparison functions to key-based sorting
from functools import cmp_to_key
def compare(x,y):
return x-y # Sort in ascending order
nums = [3, 1, 4, 2]
sorted_nums = sorted(nums, key=cmp_to_key(compare))
print(sorted_nums) # [1, 2, 3, 4]
?? Best for: Custom sorting logic without modifying the sorted() function
?? Key Takeaways
?? lru_cache() - Speeds up expensive function calls
?? reduce() - Aggregates iterable values
?? partial() - Creates preconfigured functions
?? cmp_to_key() - Custom sorting with comparison functions
#100DaysOfCode #Python #Functools #EfficientCoding #PythonTips