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.
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 please Write a function that takes a string as an argument checks whether it is...
Python please Write a function that takes a string as an argument checks whether it is a palindrome. A palindrome is a word that is the same spelt forwards or backwards. Use similar naming style e.g. name_pal. E.g. If we call the function as abc_pal(‘jason’) we should get FALSE and if we call it a abc_pal(‘pop’) we should get TRUE. Hint: define your function as abc_pal(str). This indicates that string will be passed. Next create two empty lists L1=[] and...
Write a Python function that takes a list of string as arguments. When the function is...
Write a Python function that takes a list of string as arguments. When the function is called it should ask the user to make a selection from the options listed in the given list. The it should get input from the user. Place " >" in front of user input. if the user doesn't input one of the given choices, then the program should repeatedly ask the user to pick from the list. Finally, the function should return the word...
Write a java method that takes a string and returns an array of int that contains...
Write a java method that takes a string and returns an array of int that contains the corresponding alphabetic order of each letter in the received string: An illustration: the method takes: "Sara" the method returns: {4,1,3,2} another illustration: the method takes: "hey" the method returns: {2,1,3}
USING PYTHON, write a function that takes a list of integers as input and returns a...
USING PYTHON, write a function that takes a list of integers as input and returns a list with only the even numbers in descending order (Largest to smallest) Example: Input list: [1,6,3,8,2,5] List returned: [8, 6, 2]. DO NOT use any special or built in functions like append, reverse etc.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT