progress

~/problems / Iterators & parsers / Parsers and interpreters

Fraud rules over transactions

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

hard assessment 3 levels ~60 min Stripe

Level 1 One comparison

A payments team writes rules that flag transactions for review, like amount > 100. A transaction is a dictionary from field names to values, and every value is a string: {"amount": "250", "country": "US", "card": "debit"}.

Write matches_condition(rule, txn) -> bool for a rule that is a single comparison field op literal:

  • field is a name: a letter or _, then letters, digits and _.
  • op is one of ==, !=, <, <=, >, >=.
  • literal is either a number (digits only, like 100) or a text in single quotes (like 'US'). Text has no quote inside it and may contain spaces.
  • Spaces between the parts are optional: amount>100 is the same rule as amount > 100.

How to decide:

  • If the transaction has no such field, the comparison is false, whatever the operator (even !=).
  • A number literal compares numerically. The field's value must be an integer written as an optional - and digits ("250", "-3", "007"); any other value makes the comparison false.
  • A text literal compares the strings by character codes, as Python's < on strings does.

Rules at this level are always well formed. Numbers fit in a 64-bit signed integer.

txn = {"amount": "250", "country": "US", "card": "debit"}
matches_condition("amount > 100", txn)        # True
matches_condition("country == 'GB'", txn)     # False
matches_condition("card!='credit'", txn)      # True
matches_condition("refunds >= 0", txn)        # False: no such field
matches_condition("country > 5", txn)         # False: "US" is not a number

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc