Filter Events per Subscriber with Named Rules
Arrays & HashingAuto-graded · 15 test casesLast updated
Apply an ordered list of named filter rules to every user-event pair and build a per-user list of qualifying event ids, handling missing prices, empty rule lists and unknown rule names.
Event Matching for a Mailing Campaign
A ticket marketplace wants to decide which events to mention in a promotional email to each subscriber. Which events are eligible is controlled by an ordered list of rule names. An event is suggested to a subscriber only if it satisfies every named rule.
Write a function that takes the subscribers, the events, a price table and the rule names, and returns, for each subscriber, the ids of the events that qualify.
Inputs
users: a list of dictionaries, each with string fieldsidandcity.events: a list of dictionaries, each with string fieldsidandcity.prices: a dictionary mapping event ids to ticket prices (numbers). Some events may have no entry.strategies: a list of rule names, applied in the order given.
Supported rules
"same_city": the event'scitymust be exactly equal to the user'scity."price_under_50": the event must have an entry inprices, and that price must be strictly less than 50. A price of exactly50fails. An event with no price entry fails.
Output
Return a dictionary that maps every user's id to a list of event ids.
- Each list keeps the order in which events appear in
events. - A user with no qualifying events maps to an empty list
[]. - If
strategiesis empty, every event qualifies for every user (nothing is filtering). - If two users share the same
id, the later one overwrites the earlier one in the result.
Unknown rules
If a rule name is not one of the supported ones, raise ValueError. This must happen only when that rule is actually evaluated for some user-event pair. For every pair, rules are checked in the given order and checking stops at the first rule that rejects the pair. Consequently, no error is raised if there are no users, if there are no events, or if an earlier rule rejects every pair before the unknown one is reached.
Constraints
0 <= len(users), len(events) <= 10000 <= len(strategies) <= 10- Ids and cities are strings; prices are non-negative numbers.
- City comparison is case-sensitive and exact.
Examples
Example 1
Input: match_events_to_users([{'id': 'u1', 'city': 'New York'}, {'id': 'u2', 'city': 'Boston'}], [{'id': 'e1', 'city': 'New York'}, {'id': 'e2', 'city': 'Boston'}, {'id': 'e3', 'city': 'New York'}], {'e1': 35, 'e2': 60, 'e3': 50}, ['same_city', 'price_under_50'])
Output: {'u1': ['e1'], 'u2': []}
Example 2
Input: match_events_to_users([{'id': 'u1', 'city': 'Austin'}], [{'id': 'e1', 'city': 'Austin'}, {'id': 'e2', 'city': 'Dallas'}], {'e1': 49.99, 'e2': 10}, ['price_under_50'])
Output: {'u1': ['e1', 'e2']}
Hints
Hint 1
For each user, scan the events in their given order and decide independently whether each event is kept.
Hint 2
For a given user-event pair, go through the rule names in order and stop at the first one that rejects the pair. An empty rule list means the pair is kept.
Hint 3
Raise ValueError for an unrecognised rule name only at the moment you evaluate it, not up front, so that empty inputs or earlier rejections never trigger it. Treat a missing price as a failure of the price rule.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each (user, event) pair independently. For a pair, walk through the rule names in order:
same_cityrejects the pair if the cities differ.price_under_50rejects the pair if the event has no price or the price is 50 or more.- Any other name raises
ValueError.
The first rejection stops the check for that pair. If no rule rejects it, the event id is appended to the user's list. Looping over events in input order keeps the output order correct, and starting each user with an empty list guarantees that users with no matches still appear with [].
Why it is correct
- A pair qualifies exactly when no rule rejects it, which is the logical AND of all rules. With zero rules nothing can reject, so everything qualifies.
- Because the unknown-name check happens inside the evaluation loop, it only fires when that rule is reached. Empty users or events mean the loop body never runs, and an earlier rejection breaks out before the unknown name is examined.
- Writing results into a dictionary keyed by user id makes a later duplicate id overwrite an earlier one.
- The price check uses
>= 50as the failure condition, so exactly 50 fails and 49.99 passes. A missing key is handled before the lookup.
Complexity
With U users, E events and S rules, time is O(U · E · S) in the worst case, and space is O(U · E) for the output.
A faster version would group events by city and evaluate the price rule once per event, but the straightforward approach is fine within the constraints and preserves the exact short-circuit and error semantics.
Reference solution
from typing import Dict, List
def match_events_to_users(users: List[Dict], events: List[Dict], prices: Dict[str, float], strategies: List[str]) -> Dict[str, List[str]]:
result = {}
for user in users:
matching = []
for event in events:
accepted = True
for rule in strategies:
if rule == "same_city":
if event["city"] != user["city"]:
accepted = False
break
elif rule == "price_under_50":
if event["id"] not in prices or prices[event["id"]] >= 50:
accepted = False
break
else:
raise ValueError("unknown strategy: " + rule)
if accepted:
matching.append(event["id"])
result[user["id"]] = matching
return result