Normalize a batch of phone numbers
Python data engineering interview problem. Difficulty: intermediate. Pattern: Strings. About 15 minutes. Part of the Pro drill bank.
CRM stores phone numbers in whatever format sales typed. Billing needs a normalized form so the same customer is not stored twice.
Phone numbers come in many shapes: with brackets, spaces, dashes and sometimes a leading 1 for the country. To match contacts you need one format. For each phone number, keep only the digits. If there are 11 digits and the first is 1, drop that 1. If 10 digits remain, format them as 415-555-1212. Otherwise the result is None. Return the list of results in the same order. Write normalize_phones(phones). '(415) 555-1212' and '14155551212' both become '415-555-1212'. '99' is too short, so it becomes None. The starter file already has the function name and its print lines. Keep them and fill in the body.
Requirements
- Keep only the digits of each number.
- Remove a leading country 1 when there are 11 digits.
- Format valid numbers as AAA-BBB-CCCC.
- Return None for invalid numbers.
- Keep the same order as the input.
Constraints
- phones is a list of strings and can be empty.
- A valid number has exactly 10 digits after the country digit is removed.
Examples
Input: normalize_phones(['(415) 555-1212', '14155551212', '99']) Output: ['415-555-1212', '415-555-1212', None] This input follows the stated rules and produces this output.
Topics: lakebench, python, data-transformation.
More Python interview questions · All interview problems · Learn data engineering
Normalize a batch of phone numbers
Interview-style drill: Reformat a list of inconsistently formatted phone numbers into one standard shape.
Normalize a batch of phone numbers to a single comparable form.