Code Explanation:
1. Defining the factory Function
def factory(n):
return lambda x: x ** n
Explanation:
factory is a function that takes a parameter n.
It returns a lambda function that takes x and returns x ** n (i.e., x raised to the power n).
This is a function factory – it generates power functions dynamically.
Example:
factory(2) will return a function that squares its input (x ** 2)
factory(3) will return a function that cubes its input (x ** 3)
2. Creating the square Function
square = factory(2)
Explanation:
Calls factory(2), which returns lambda x: x ** 2
So square is now a function that returns the square of any input.
Example:
square(3) → 3 ** 2 = 9
3. Creating the cube Function
cube = factory(3)
Explanation:
Calls factory(3), which returns lambda x: x ** 3
So cube is now a function that returns the cube of any input.
Example:
cube(2) → 2 ** 3 = 8
4. Printing the Results
print(square(3), cube(2))
Explanation:
square(3) → 3 ** 2 = 9
cube(2) → 2 ** 3 = 8
Output:
9 8
.png)

0 Comments:
Post a Comment