Medium: Interview Core · Problem 58 of 82

Extract the Prices

MediumStandard LibraryPython

Write extract_prices(text) that finds every price in a piece of text and returns them as a list of floats, in the order they appear.

A price is a dollar sign $ immediately followed by digits, optionally with thousands commas (1,234) and optionally exactly two decimal digits (.50). Numbers without a $ are not prices.

Understand the problem

Build the pattern in pieces.

In a regular expression, what does \$ match?

  1. The end of the line
  2. A literal dollar sign
  3. Any character

In a pattern $ normally means "end of the line", so a literal dollar sign must be escaped with a backslash: \$. Use a raw string (r"...") so Python does not treat the backslash itself as an escape.

Which pattern matches a whole number such as 1,234 or 12?

  1. \d+
  2. \d{1,3}(?:,\d{3})+|\d+
  3. [0-9]*

First try digits with comma groups (1,234 or 1,234,567): one to three digits, then one or more groups of a comma and three digits. If that does not match, fall back to plain digits. The (?:...) is a group that does not capture.

What does re.finditer(pattern, text) give?

  1. A list of strings
  2. An iterator of match objects, with .group(1) for each captured part
  3. The first match only

finditer yields a match object for every non-overlapping match. A match has .group(0) (the whole match) and .group(1), .group(2) for the parenthesised parts.

Write the solution

Return the list of floats.

def extract_prices(text):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which three parts does a price have, and which of them are optional?

Hint 2: the shape of the answer

Pattern: \$ then a group for the whole-number part (with commas), then an optional group for \.\d{2}. For each match remove the commas from group 1, add group 2 if present, and convert with float.

Reflect

Solution

import re

PRICE = re.compile(r"\$(\d{1,3}(?:,\d{3})+|\d+)(\.\d{2})?")

def extract_prices(text):
    prices = []
    for match in PRICE.finditer(text):
        whole = match.group(1).replace(",", "")
        cents = match.group(2) or ""
        prices.append(float(whole + cents))
    return prices

What this tests: regular expressions (re.compile, finditer, groups, alternation, optional parts, escaping), and converting matched text.

Build patterns in small steps and test each on awkward text. A regex that works on three examples can fail on the fourth.

Order of alternatives matters: \d{1,3}(?:,\d{3})+|\d+ tries the comma form first. If you wrote \d+ first, $1,234 would match only $1.

Compile once: re.compile at module level avoids rebuilding the pattern on every call.

When not to use a regex: for nested or structured formats (HTML, JSON, CSV, dates) use the proper parser. Regexes are for flat patterns in text.

What an interviewer might ask next: Make the dollar sign optional and also accept the currency code ("USD 5.00"). Why does it make the pattern ambiguous? (Plain numbers such as years would match.)