Fix the US phone number formatter

Review the AI's codeEasy10 min

Your task

You asked an AI for a phone number formatter, and its first answer imported phone-formatter-pro, a package nobody on your team had heard of. You asked for plain code with no dependencies instead, so you can read every line before it ships.

An assistant wrote format_us_phone(raw). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • raw: the phone number as someone typed it. It can hold any characters.
  • Return the formatted number, or "invalid".

Rules the tests check:

  • Keep only the digits 0 to 9 from raw, in order. Every other character is ignored.
  • Exactly 10 digits: return "(AAA) BBB-CCCC", where AAA is the first 3 digits, BBB the next 3 and CCCC the last 4.
  • Exactly 11 digits starting with 1: a US number with its country code. Drop the 1 and return "+1 " followed by the 10 digit format above.
  • Any other number of digits, or 11 digits that do not start with 1, returns "invalid".

Examples

format_us_phone(raw: str) -> str
Example 1
Inputformat_us_phone("5551234567")
Output"(555) 123-4567"
Example 2
Inputformat_us_phone("+1 (555) 123-4567")
Output"+1 (555) 123-4567"