Question

In: Computer Science

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 the digits match the pattern. If asked to create a phone number that does not meet the pattern above, I should throw a ValueError with a string explaining the problem: too many or too few digits, or the wrong digits.

For example, the strings below

+1 (617) 495-4024

617-495-4024

1 617 495 4024

617.495.4024

should all produce an object that is printed as (617) 495-4024

ValueErrors

Each of the following strings should produce a ValueError exception.

+1 (617) 495-40247 has too many digits

(617) 495-402 has too few digits

+2 (617) 495-4024 has the wrong country code

(017) 495-4024 has an illegal area code

(617) 195-4024 has an illegal exchange code

class Phone:
"A Class defining valid Phone Numbers"
  
def __init__(self, raw):
"Create new instance"
self.number = self._normalize(raw)

def __str__(self) -> str:
"Create printable representation"
pass

def area_code(self) -> str:
"Return the area code"
pass

def _normalize(self, raw: str) -> str:
""""Take string presented and return string with digits
Throws a ValueError Exception if not a NANP number"""
pass

Solutions

Expert Solution


class Phone:

    "A Class defining valid Phone Numbers"

    def __init__(self, raw):

        "Create new instance"

        self.number = self._normalize(raw)

    def __str__(self) -> str:

        "Create printable representation"

        # remove area code

        if self.number[0] == '1':

            return f'({self.number[1:4]}) {self.number[4:7]}-{self.number[7:]}'

        return f'({self.number[0:3]}) {self.number[3:6]}-{self.number[6:]}'

        pass

    def area_code(self) -> str:

        return str(self.number[0]) + str(self.number[1]) + str(self.number[2])

    def _normalize(self, raw: str) -> str:

        """"Take string presented and return string with digits

        Throws a ValueError Exception if not a NANP number"""

        # string to return

        number = ""

        for digit in raw:

            if digit.isdigit():

                number += digit

        if number[0] == '1':

            if len(number) > 11:

                raise ValueError(raw)

        elif len(number) > 10:

            raise ValueError(raw)

        return number

# testing

# For example, the strings below


try:

    print(Phone("+1 (617) 495-4024"))

    print(Phone("617-495-4024"))

    print(Phone("1 617 495 4024"))

    print(Phone("617.495.4024"))

    # should all produce an object that is printed as (617) 495-4024

    # following string should produce a ValueError exception.

    print(Phone("+1 (617) 495-40247"))

except ValueError as raw:

    print("error in ", raw)

    pass

.

Screenshot:

Output:

.


Related Solutions

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...
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 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
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName,...
How would I setup this dictionary for Python 3? class Student(object): def __init__(self, id, firstName, lastName, courses = None): The “id”, “firstName” and “lastName” parameters are to be directly assigned to member variables (ie: self.id = id) The “courses” parameter is handled differently. If it is None, assign dict() to self.courses, otherwise assign courses directly to the member variable. Note: The “courses” dictionary contains key/value pairs where the key is a string that is the course number (like “course1”) and...
Python: How would I write a function that takes a directory and a size in bytes,...
Python: How would I write a function that takes a directory and a size in bytes, and returns a list of files in the directory or below that are larger than the size. For example, I can use this function to look for files larger than 1 Meg below my Home directory.
Python: How would I write a function that takes a URL of a webpage and finds...
Python: How would I write a function that takes a URL of a webpage and finds the first link on the page? The hint given is the function should return a tuple holding two strings: the URL and the link text.
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 %...
Python: What are the defintions of the three method below for a class Date? class Date(object):...
Python: What are the defintions of the three method below for a class Date? class Date(object): "Represents a Calendar date"    def __init__(self, day=0, month=0, year=0): "Initialize" pass def __str__(self): "Return a printable string representing the date: m/d/y" pass    def before(self, other): "Is this date before that?"
Which of this method of class String is used to obtain a length of String object?...
Which of this method of class String is used to obtain a length of String object? What is the output of the below Java program with WHILE, BREAK and CONTINUE? int cnt=0; while(true) { if(cnt > 4)    break;    if(cnt==0) {     cnt++; continue; }   System.out.print(cnt + ",");   cnt++; } 1,2,3,4 Compiler error 0,1,2,3,4, 1,2,3,4,
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT