requests_per_user["alice"] is 5, which is equal to user_limit (5), so the first if condition is true.
Step 2: Determine which print runs
Since the first condition is true, it prints "User limit reached" and skips the rest.
Final Answer:
User limit reached -> Option B
Quick Check:
5 >= 5 triggers user limit [OK]
Hint: Check user count first; equal means limit reached [OK]
Common Mistakes:
Thinking IP limit triggers first
Ignoring >= condition
Assuming else runs when equal
4. This code snippet is intended to enforce per-IP rate limits but has a bug:
requests_per_ip = {"1.2.3.4": 8}
ip_limit = 10
ip = "1.2.3.4"
if requests_per_ip[ip] > ip_limit:
print("Limit exceeded")
else:
print("Allowed")
What is the bug and how to fix it?
medium
A. Bug: Uses > instead of >=; fix by changing to >=.
B. Bug: ip variable is wrong type; fix by converting to string.
C. Bug: requests_per_ip key missing; fix by adding default value.
D. Bug: prints wrong message; fix by swapping print statements.
Solution
Step 1: Analyze condition logic
The code blocks requests only if requests_per_ip[ip] > ip_limit, so if requests equal ip_limit, it allows the request.
Step 2: Fix condition to include equal case
Change > to >= so requests equal to ip_limit also get blocked.
Final Answer:
Bug: Uses > instead of >=; fix by changing to >=. -> Option A
Quick Check:
Use >= to block at limit [OK]
Hint: Use >= to block requests at limit, not just above [OK]
Common Mistakes:
Ignoring equal case in condition
Assuming IP variable type is wrong
Thinking missing keys cause this bug
5. You want to implement a rate limiter that blocks requests if either the user or the IP address exceeds their limits. Which pseudocode correctly enforces this combined rule?
hard
A. if requests_per_user[user] > user_limit and requests_per_ip[ip] > ip_limit:
block_request()
B. if requests_per_user[user] == user_limit and requests_per_ip[ip] == ip_limit:
block_request()
C. if requests_per_user[user] < user_limit or requests_per_ip[ip] < ip_limit:
block_request()
D. if requests_per_user[user] > user_limit or requests_per_ip[ip] > ip_limit:
block_request()
Solution
Step 1: Understand combined blocking logic
The request should be blocked if either the user or the IP exceeds their limit, so the condition must use OR.
Step 2: Check condition correctness
if requests_per_user[user] > user_limit or requests_per_ip[ip] > ip_limit:
block_request() uses OR with > comparisons, correctly blocking if user or IP exceeds limits.
Final Answer:
if requests_per_user[user] > user_limit or requests_per_ip[ip] > ip_limit:
block_request() -> Option D
Quick Check:
Block if user OR IP exceeds limit [OK]
Hint: Use OR to block if either user or IP exceeds limit [OK]