In: Computer Science
Write Python class that takes a string and returns with a valid phone number.
Number format is ten-digit numbers consisting of a three-digit area code and a seven-digit number.
Clean up different telephone numbers by removing punctuation, and removing incorrect format and the country code (1).
You should throw a ValueError with a string if there are too many or too few digits, or the wrong digits.
For example, the strings: +1 (617) 111-0000, 617-111-0000, 1 617 111 0000, 617.111.0000 should end up with (617) 111-0000
Sample and incomplete starting code:
class Phone:
def __init__(self, raw):
self.number =
self._normalize(raw)
def __str__(self) ->
str:
def area_code(self) ->
str:
def _normalize(self, raw: str) ->
str:
Throws a ValueError Exception
import re class Phone: REGEX_SANITIZE = re.compile(r'[^\d]') REGEX_STRIP_1 = re.compile(r'\A1(\d{10})\Z') REGEX_PARTS = re.compile(r'\A(\d{3})(\d{3})(\d{4})\Z') INVALID = ("000", "000", "0000") PRETTY_FORMAT = "(%s) %s-%s" def __init__(self, number_string): self.parts = self._parse(self._clean(number_string)) self.number = "".join(self.parts) def area_code(self): return self.parts[0] def pretty(self): return Phone.PRETTY_FORMAT % self.parts def _clean(self, number_string): clean = Phone.REGEX_SANITIZE.sub("", number_string) clean = Phone.REGEX_STRIP_1.sub(r"\1", clean) return clean def _parse(self, clean_number_string): match = Phone.REGEX_PARTS.search(clean_number_string) if match: return match.groups() else: return Phone.INVALID
Explanation:
Using regexps to remove a leading "1" from a string or to split it in 3 parts is really a case of "is all you have is a hammer".
Also:
class attributes can be looked up directly on the instance (so no need to hardcode the class name in a method) you expose both .number and .parts as public attributes. The first is required by the testcase, but it doesn't mean you shouldn't maintain invariants. Wether the second should be part of the API is debatable, but if you choose to do so you here again have to maintain the invariants.