Intermediate
Build a token bucket
Write TokenBucket(capacity, refill_per_sec) with try_take(now_ms). It starts full. It returns 0 when a request is allowed (and uses one token), otherwise the number of milliseconds to wait until one token is back, rounded up.
To keep every number whole, store tokens times 1000. Between calls the bucket gains (now_ms - last_ms) * refill_per_sec thousandths of a token, never more than capacity * 1000. Update the last-seen time on every call, allowed or not.
What Check tests
- A full bucket of 2 allows two requests at once
- The third request must wait 1000 ms
- After waiting 500 ms it still has to wait 500 ms more
- After 1000 ms a token is back
- The bucket never holds more than its capacity
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.