Question

In: Computer Science

Write Python class that takes a string and returns with a valid phone number. Number format...

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

Solutions

Expert Solution

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.


Related Solutions

Use Python Write a function that takes a mobile phone number as a string and returns...
Use Python Write a function that takes a mobile phone number as a string and returns a Boolean value to indicate if it is a valid number or not according to the following rules of a provider: * all numbers must be 9 or 10 digits in length; * all numbers must contain at least 4 different digits; * the sum of all the digits must be equal to the last two digits of the number. For example '045502226' is...
Python: How would I modify the class below that takes a string and returns an object...
Python: How would I modify the class below that takes a string and returns an object holding a valid NANP phone number. I am asked to filll in the three methods listed, but underfined, below: __str__(), area_code(), and normalize(). My task is to clean up differently formatted telephone numbers by removing punctuation, such as '(', '-', and the like, and removing and the country code (1) if present. I am asked to start by stripping non-digits, and then see if...
Write a function named "characters" that takes a string as a parameter and returns the number...
Write a function named "characters" that takes a string as a parameter and returns the number of characters in the input string
For python Write a new method for the Fraction class called mixed() which returns a string...
For python Write a new method for the Fraction class called mixed() which returns a string that writes out the Fraction in mixed number form. Here are some examples: f1 = Fraction(1, 2) print(f1.mixed()) # should print "1/2" f2 = Fraction(3, 2) print(f2.mixed()) # should return "1 and 1/2" f3 = Fraction(5, 1) print(f3.mixed()) # should return "5" def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm %...
Write a PYTHON function CommonLetters(mystring) that takes mystring as input and returns the number of letters...
Write a PYTHON function CommonLetters(mystring) that takes mystring as input and returns the number of letters in mystring that also occur in the string ‘Python’. Using above function, write a program that repeatedly prompts the user for a string and then prints the number of letters in the string that are also in string ‘Python’. The program terminates when the user types an empty string.
Write a function that takes a valid stringlist and returns the index of the smallest element...
Write a function that takes a valid stringlist and returns the index of the smallest element in the list represented by the stringlist. You may not use split(). Examples: >>> stringlist min index('[123,53,1,8]') # 1 is smallest2 >>> stringlist min index('[1,2,345,0]') # 0 is smallest3 >>> stringlist min index('[5] ') # 5 is smallest0
python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
Python Implement function noVowel() that takes a string s as input and returns True if no...
Python Implement function noVowel() that takes a string s as input and returns True if no char- acter in s is a vowel, and False otherwise (i.e., some character in s is a vowel). >>> noVowel('crypt') True >>> noVowel('cwm') True >>> noVowel('car') False
Write a Python function that takes a list of integers as a parameter and returns the...
Write a Python function that takes a list of integers as a parameter and returns the sum of the elements in the list. Thank you.
Write a Python function that takes a list of integers as a parameter and returns the...
Write a Python function that takes a list of integers as a parameter and returns the sum of the elements in the list. Thank you.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT