-
Notifications
You must be signed in to change notification settings - Fork 0
Python
Python Questions
- Decorator Usage: Write a Python decorator that logs the time taken by a function to execute.
You can create a Python decorator that logs the time taken by a function to execute using the time module. Here's an example implementation:
import time
def calculate_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f"Function '{func.__name__}' took {execution_time:.4f} seconds to execute.")
return result
return wrapper
# Example usage:
@calculate_time
def example_function(n):
# Some time-consuming operation
time.sleep(n)
return "Done"
result = example_function(2)
print(result)
In this example:
- We define a decorator
calculate_time
that takes a functionfunc
as input. - Inside the decorator, we define a wrapper function that records the start time before calling the original function (
func
) and the end time after the function execution. - We calculate the execution time by subtracting the start time from the end time.
- Finally, we print the execution time and return the result of the original function.
- We apply the decorator
@calculate_time
to the example_function to log the time taken by it to execute.
You can decorate any function you want to measure the execution time by simply adding @calculate_time
before its definition.
-
List Comprehension: Use list comprehension to create a list of squares of numbers from 1 to 10.
-
Counter Usage: Given a list of words, use the Counter class from the collections module to count the frequency of each word.
-
Generator Function: Write a generator function that yields the Fibonacci sequence indefinitely.
Here’s a generator function that yields the Fibonacci sequence indefinitely:
def fibonacci_sequence():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
You can use this generator to generate Fibonacci numbers on demand. For example:
fib_gen = fibonacci_sequence()
for _ in range(10):
print(next(fib_gen))
This will print the first 10 Fibonacci numbers. You can continue calling next(fib_gen)
to generate more Fibonacci numbers as needed.
-
Context Manager: Implement a context manager that measures the execution time of a code block using the
with
statement.
You can implement a context manager to measure the execution time of a code block using the with statement like this:
import time
class Timer:
def __enter__(self):
self.start_time = time.time()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.end_time = time.time()
elapsed_time = self.end_time - self.start_time
print(f"Execution time: {elapsed_time} seconds")
# Example usage:
with Timer():
# Code block to measure execution time
time.sleep(2) # Placeholder for actual code
This context manager measures the time taken for the code block inside the with statement to execute and prints the elapsed time once the block exits. You can replace the time.sleep(2)
with the actual code you want to measure.
-
Lambda Function: Use a lambda function to sort a list of tuples based on the second element of each tuple.
-
Map and Filter: Use map and filter functions to convert a list of strings to uppercase and filter out strings containing vowels.
-
Partial Function Application: Use the
functools.partial
function to create a partial function that adds a fixed value to any number. -
JSON Parsing: Given a JSON string, parse it using the
json
module and extract specific data fields. -
Regular Expressions: Write a regular expression to validate email addresses.
-
File Handling: Read data from a CSV file using the
csv
module and calculate the total sum of a specific column. -
Class Inheritance: Create a class hierarchy with a base class and multiple derived classes, demonstrating inheritance and method overriding.
-
Exception Handling: Write code that demonstrates the use of try-except blocks to handle exceptions gracefully.
-
Dictionary Comprehension: Use dictionary comprehension to create a dictionary mapping each word in a list to its length.
-
Generator Expression: Use a generator expression to generate all prime numbers less than 1000.
-
Pickle Usage: Serialize and deserialize a Python object using the
pickle
module. -
Assertions: Write assertions to validate certain conditions in a function and raise appropriate errors if the conditions are not met.
-
Contextlib Module: Use the
contextlib
module to create a context manager that suppresses a specific type of exception. -
String Formatting: Use f-strings or the
format
method to format strings with placeholders for variables. -
Datetime Module: Write code to calculate the difference between two dates using the
datetime
module.