medium +20 pts

Rate Limit Decorator

Build a decorator that limits how often a function can be called per second.

Write a decorator `rate_limit(max_per_second)` that wraps a function and ensures it is called at most `max_per_second` times per sliding second. If the function is called more than that, the decorator should raise a `RuntimeError` with message `'Rate limit exceeded'` (without raising for allowed calls). Time should be measured using `time.monotonic()`. The decorator must preserve the wrapped function's metadata (use `functools.wraps`). The wrapped function should work exactly as the original for allowed calls. Implement the function `rate_limit(max_per_second)` that returns a decorator. The function signature you must implement is: ```python def rate_limit(max_per_second): ... ``` **Notes:** - `max_per_second` is a positive integer. - The limit is per sliding window of 1 second. Calls older than 1 second do not count. - The decorator should work for any callable (including methods). - You may assume the function is called sequentially (not from multiple threads).

Constraints

- `max_per_second` is a positive integer (>=1). - Use only the standard library. - The wrapped function may be called many times; your solution should be efficient enough for up to 10^5 calls in tests.

Example

```python
import time

@rate_limit(max_per_second=2)
def greet(name):
    return f"Hello {name}"

print(greet("Alice"))  # Hello Alice
print(greet("Bob"))    # Hello Bob
try:
    greet("Charlie")   # raises RuntimeError: Rate limit exceeded
except RuntimeError as e:
    print(e)            # Rate limit exceeded

time.sleep(1)
print(greet("Dave"))   # Hello Dave
```
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Keep a list of timestamps of recent calls; prune those older than 1 second before checking.
Use `time.monotonic()` for timestamps to avoid system clock changes.
Use `functools.wraps` to preserve the original function's `__name__` and `__doc__`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.