Partial Functions in Python
Level 5217 keystrokes
This uses partial to create specialized functions with preset arguments. Partial application fixes some arguments, creating a new function.
Python code
# Import partial from functools module1from functools import partial2 # Define a general power function with two parameters3def power(base, exponent): # Calculate base raised to exponent4 return base ** exponent5 # Create a square function by fixing exponent=2# square(x) is equivalent to power(x, exponent=2)6square = partial(power, exponent=2)# Create a cube function by fixing exponent=37cube = partial(power, exponent=3)8 # Use the specialized functions - only need to provide base9print(f"square(5) = {square(5)}")10print(f"cube(5) = {cube(5)}")Output
square(5) = 25 cube(5) = 125
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 9)× 9=× 6"× 4,× 3{× 2}× 2*× 2:× 1