Detect repeated authentication failures
Group failed logons and apply a documented threshold without counting successful events.
A count needs a definition
Repeated failures can suggest password guessing, a stale saved password, or a broken integration. A count is a lead for investigation. Define the event set, account normalization, time window, and threshold before interpreting the result.
This lesson receives events already selected for a window. Count only events whose outcome is failure. The exercise treats surrounding whitespace and letter case as irrelevant to account identity, so use strip().casefold(). This is a policy for these supplied exports; real identity systems can have different rules.
Group records without losing numeric types
collections.Counter counts repeated keys. An ordinary dictionary and a loop work too. Keep the count as an integer, then return small dictionaries containing a normalized user and failure count. Sort by user so repeated runs produce an easily compared report.
An inclusive threshold of three means three or more failures. A success between failures does not reset the count for this rule. A consecutive-failure detector would be a different rule and would need different tests.
Reject zero, negative numbers, booleans, and fractional thresholds. Python considers booleans a kind of integer, so type(threshold) is int is useful for this particular configuration contract. The task is deliberately explicit about the boundary so the checks can verify the behavior rather than a preferred implementation.
from collections import Counter
users = [" alex ", "Alex", "sam"]
print(Counter(user.strip().casefold() for user in users))
Put it into practice.
Define repeated_failures(events, threshold). Count only failure outcomes, grouping users by strip().casefold(). Return dictionaries with user and integer failures, sorted by user, for counts >= threshold. Successes do not reset counts. Reject thresholds that are not positive integers, including booleans, with ValueError. The events are already validated and windowed.
See an explained solution
from collections import Counter
def repeated_failures(events, threshold):
if type(threshold) is not int or threshold < 1:
raise ValueError("Threshold must be a positive integer")
counts = Counter(event["user"].strip().casefold() for event in events if event["outcome"] == "failure")
return [{"user": user, "failures": counts[user]} for user in sorted(counts) if counts[user] >= threshold]
Filtering first keeps successes out of the count. A normalized grouping key joins the intended account variants, and sorting makes the result stable.