Challenge: Create Your First Python Decorator
Tehtävä
Swipe to start coding
Sometimes, it's necessary to measure how long a particular function or code segment takes to execute. This can be achieved by calculating the time elapsed from the start to the end of the function. However, if you need to measure the execution time of multiple functions, a more efficient approach would be to write a single decorator and apply it to these functions.
We'll develop such a decorator and see its effectiveness:
- You need to define the parameters that the wrapper will accept;
- Call the
func
function with the arguments *args and **kwargs, and assign it to theresult
variable; - In the line return ___, you should return
result
; - Complete the decorator by returning the wrapper function;
- Applies the
time_it
decorator to thefactorial
function; - Calls the
factorial
function (which is now decorated with time_it) and prints its return value.
Ratkaisu
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time
# Step 2: Define the decorator
def time_it(func):
def wrapper(*args, **kwargs):
start_time = time.time() # Start time
result = func(*args, **kwargs) # Call the function
end_time = time.time() # End time
print(f"{func.__name__} took {end_time - start_time} seconds")
return result
return wrapper
# Step 4: Apply the decorator
@time_it
def factorial(n):
"""Function to compute factorial of a number"""
return 1 if n == 0 else n * factorial(n - 1)
# Step 5: Test the decorator
print(factorial(10)) # Replace with any number to test
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 5. Luku 3
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time
# Step 2: Define the decorator
def time_it(func):
def wrapper(___, ___):
start_time = time.time() # Start time
result = ___(*args, **kwargs) # Call the function
end_time = time.time() # End time
print(f"{func.__name__} took {end_time - start_time} seconds")
return ___
return ___
# Step 4: Apply the decorator
@___
def factorial(n):
"""Function to compute factorial of a number"""
return 1 if n == 0 else n * factorial(n - 1)
# Step 5: Test the decorator
print(___(10)) # Replace with any number to test
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme