Let's compare the fibonacci function with and without memoization to understand the performance difference.
Here's the fibonacci function without memoization:
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
def create_multiplier(factor): | |
return lambda x: x * factor | |
# Create specific multiplier functions | |
double = create_multiplier(2) | |
triple = create_multiplier(3) | |
# Use the created functions | |
print(double(5)) # Output: 10 | |
print(triple(5)) # Output: 15 |
def create_multiplier(n): | |
def multiplier(x): | |
return x * n | |
return multiplier | |
# Creating specific multiplier functions | |
multiply_by_2 = create_multiplier(2) | |
multiply_by_3 = create_multiplier(3) | |
# Using the returned functions |
def apply_operation(operation, x, y): | |
return operation(x, y) | |
# Functions to pass as arguments | |
def add(x, y): | |
return x + y | |
def multiply(x, y): | |
return x * y |
def create_multiplier(factor): | |
"""Returns a function that multiplies its input by the given factor.""" | |
def multiplier(x): | |
return x * factor | |
return multiplier | |
# Create specific multiplier functions | |
double = create_multiplier(2) | |
triple = create_multiplier(3) |
def double(n): | |
return n * 2 | |
def map_function(func, values): | |
result = [] | |
for value in values: | |
result.append(func(value)) | |
return result | |
# Use the custom map function |
def add(a, b): | |
return a + b | |
result = add(3, 4) | |
print(add) # Prints the function object | |
print(result) # Prints 7 |