Given a list of raw transaction strings transactions and a list of categorization rules, categorize each transaction based on keyword matching.
Each rule is a pair [keyword, category]. For each transaction, find the first rule whose keyword appears as a substring (case-insensitive) in the transaction string and assign that category. If no rule matches, assign the category "Other".
Return a list of strings where the i-th element is the category assigned to transactions[i].
Function Signature
def categorize_transactions(transactions: list[str], rules: list[list[str]]) -> list[str]:
Rules
-
"First rule" means first in the order of
rules
. When several keywords appear in a transaction, the rule with the smallest index wins, wherever its keyword sits in the string.
-
Matching ignores letter case on both sides. The assigned category is returned exactly as written in the rule.
-
Matching is a plain substring test. A keyword can match inside a longer word, and spaces and punctuation in a keyword must appear exactly as given.
-
The output has one entry per transaction, in input order.
Constraints
-
1 <= len(transactions) <= 1000
-
1 <= len(transactions[i]) <= 200
-
1 <= len(rules) <= 100
-
Each rule is a list of two strings:
[keyword, category]
-
1 <= len(keyword) <= 50
-
1 <= len(category) <= 50
Examples
Input: transactions = ["Starbucks Coffee #1234", "Amazon.com Purchase", "Shell Gas Station", "Netflix Subscription", "Walmart Grocery"],
rules = [["Starbucks", "Food and Drink"], ["Amazon", "Shopping"], ["Shell", "Transportation"], ["Netflix", "Entertainment"], ["Walmart", "Groceries"]]
Output: ["Food and Drink", "Shopping", "Transportation", "Entertainment", "Groceries"]
Each transaction contains exactly one keyword: "Starbucks", "Amazon", "Shell", "Netflix" and "Walmart" respectively, so each gets that rule's category.
Input: transactions = ["STARBUCKS downtown", "unknown vendor payment", "amazon prime video"],
rules = [["starbucks", "Food and Drink"], ["amazon", "Shopping"], ["prime video", "Entertainment"]]
Output: ["Food and Drink", "Other", "Shopping"]
"STARBUCKS downtown" matches "starbucks" once case is ignored. "unknown vendor payment" matches no keyword, so it gets "Other". "amazon prime video" contains both "amazon" and "prime video", and the "amazon" rule comes first in the list.
Input: transactions = ["Prime Video charge billed by Amazon", "Uber Eats order", "Uber trip"],
rules = [["uber eats", "Food and Drink"], ["uber", "Transportation"], ["amazon", "Shopping"], ["prime video", "Entertainment"]]
Output: ["Shopping", "Food and Drink", "Transportation"]
In the first transaction "prime video" appears earlier in the string, but the "amazon" rule has the smaller index, so it wins. "Uber Eats order" matches the first rule before the broader "uber" rule is checked, and "Uber trip" only matches "uber".