Answer A: Anthropic Claude Opus 4.6
import time class TokenBucket: """A token bucket rate limiter. Tokens are added at a constant `refill_rate` (tokens per second) up to `capacity`. Each call to `allow_request()` tries to consume one token. """ def __init__(self, capacity: int, refill_rate: float) -> None: """ Args: capacity: Maximum number of tokens the bucket can hold. refill_rate: Number of tokens added to the bucket per second. """ self.capacity: int = capacity self.refill_rate: float = refill_rate self.tokens: float = float(capacity) # start full...
Show Full Answer ▼
import time class TokenBucket: """A token bucket rate limiter. Tokens are added at a constant `refill_rate` (tokens per second) up to `capacity`. Each call to `allow_request()` tries to consume one token. """ def __init__(self, capacity: int, refill_rate: float) -> None: """ Args: capacity: Maximum number of tokens the bucket can hold. refill_rate: Number of tokens added to the bucket per second. """ self.capacity: int = capacity self.refill_rate: float = refill_rate self.tokens: float = float(capacity) # start full self.last_refill_time: float = time.monotonic() def _refill(self) -> None: """Add tokens based on elapsed time since the last refill.""" now = time.monotonic() elapsed = now - self.last_refill_time tokens_to_add = elapsed * self.refill_rate self.tokens = min(self.capacity, self.tokens + tokens_to_add) self.last_refill_time = now def allow_request(self) -> bool: """Attempt to consume one token. Returns: True if the request is allowed (a token was available and consumed), False otherwise. """ self._refill() if self.tokens >= 1: self.tokens -= 1 return True return False # --------------------------------------------------------------------------- # Quick demo / smoke test # --------------------------------------------------------------------------- if __name__ == "__main__": bucket = TokenBucket(capacity=5, refill_rate=2) # 5 max, 2 tokens/sec # Burst: should allow 5 requests immediately for i in range(7): result = bucket.allow_request() print(f"Request {i + 1}: {'allowed' if result else 'denied'}") # Wait a bit for tokens to refill print("\nSleeping 1.5 seconds...") time.sleep(1.5) # should refill ~3 tokens for i in range(5): result = bucket.allow_request() print(f"Request {i + 1}: {'allowed' if result else 'denied'}")
Result
Winning Votes
0 / 3
Average Score
Total Score
Overall Comments
Answer A provides a clean, correct, and well-documented implementation of the TokenBucket class. It uses time.monotonic() for accurate timing, correctly refills tokens based on elapsed time, caps tokens at capacity, and consumes one token per allowed request. The code is readable with good docstrings and includes a helpful demo/smoke test. However, it lacks thread safety (no locking mechanism), which is a notable omission for a rate limiter that would typically be used in concurrent environments. It also lacks input validation for constructor arguments.
View Score Details ▼
Correctness
Weight 35%The core logic is correct: tokens are refilled based on elapsed time using time.monotonic(), capped at capacity, and one token is consumed per allowed request. However, the lack of thread safety means the implementation could produce incorrect results in concurrent usage due to race conditions.
Completeness
Weight 20%The implementation covers all required elements: constructor with capacity and refill_rate, allow_request() method, and internal state management. It includes a runnable demo. However, it is missing thread safety and input validation, which are important for a complete implementation.
Code Quality
Weight 20%The code is clean, readable, and well-documented with clear docstrings and type hints. Variable names are descriptive. The separation of refill logic into a private method is good design. Minor deduction for lack of private attribute naming conventions.
Practical Value
Weight 15%The implementation is practically useful for single-threaded scenarios and includes a helpful demo. However, the lack of thread safety significantly limits its practical value in real-world applications where rate limiters are typically used in concurrent environments.
Instruction Following
Weight 10%Follows all instructions: implements TokenBucket class in Python, constructor accepts capacity and refill_rate, allow_request() takes no arguments and returns True/False while consuming a token. Uses only standard library (time module). State is managed within the instance.
Total Score
Overall Comments
Answer A provides a correct and well-written implementation for a single-threaded environment. Its strengths are clean code with modern Python type hints, clear logic, and an excellent runnable demo that verifies its behavior. However, its major weakness is the lack of thread safety, which makes it unsuitable for most real-world applications of a rate limiter where concurrent requests are common.
View Score Details ▼
Correctness
Weight 35%The implementation is logically correct for a single-threaded context. The token refill calculation and capacity limiting are implemented properly. However, it is not correct in a concurrent environment, which is a common use case for this algorithm.
Completeness
Weight 20%The answer is very complete, providing not just the class implementation but also a runnable demo script under `if __name__ == "__main__":`. This demo effectively showcases the burst and refill behavior, making it easy to understand and verify.
Code Quality
Weight 20%The code quality is high. It uses modern Python features like type hints, has clear docstrings, and follows good naming conventions. The logic is well-structured with a private helper method for refilling.
Practical Value
Weight 15%The practical value is limited because the implementation is not thread-safe. Rate limiters are almost always used in concurrent environments (like web servers), where this implementation would be subject to race conditions and would not work reliably.
Instruction Following
Weight 10%The answer perfectly follows all instructions in the prompt, implementing the specified class, constructor, and method with the correct logic. The solution is self-contained.
Total Score
Overall Comments
Answer A provides a correct and readable Python implementation of a token bucket. It uses a monotonic clock, tracks internal state properly, refills based on elapsed time, caps tokens at capacity, and consumes one token per allowed request. The main weaknesses are lack of input validation, no protection for concurrent access, and a basic float-based approach without addressing precision concerns mentioned in the prompt. The included demo is helpful but not necessary for the core task.
View Score Details ▼
Correctness
Weight 35%The refill and consumption logic are correct: elapsed time is measured with a monotonic clock, tokens are added proportionally, capped at capacity, and one token is consumed when available. It handles first use and long idle periods properly. The score is held back because it does not address invalid parameters and uses straightforward floating-point accumulation without any mitigation.
Completeness
Weight 20%It includes the required constructor, internal state, and allow_request method, and the implementation is self-contained. However, it does not cover parameter validation or discuss edge conditions such as invalid capacity or refill rate.
Code Quality
Weight 20%The code is clean, readable, and idiomatic, with good naming and helpful docstrings. The structure is simple and easy to follow. It loses some points because the public state is exposed directly and the extra demo code is not part of the core implementation.
Practical Value
Weight 15%It is usable for simple single-threaded scenarios and demonstrates behavior with a quick smoke test. In more realistic settings, the lack of validation and thread safety reduces operational usefulness.
Instruction Following
Weight 10%It follows the task well by implementing a self-contained TokenBucket class with the required constructor and allow_request behavior. The only slight issue is inclusion of extra demo code beyond the requested core answer.