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
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...
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: 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.
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,
Python please A string is one of most powerful data types in programming. A string object...
Python please A string is one of most powerful data types in programming. A string object is a sequence of characters and because it is a sequence, it is indexable, using index numbers starting with 0. Similar to a list object, a string object allows for the use of negative index with -1 representing the index of the last character in the sequence. Accessing a string object with an invalid index will result in IndexError exception. In Python a string...
Java RECURSIVE methods: => intersection(String s1, String s2): takes two strings and returns the string consisting...
Java RECURSIVE methods: => intersection(String s1, String s2): takes two strings and returns the string consisting of all letters that appear in both s1 and s2. => union(String s1, String s2): takes two strings and returns the string consisting of all letters that appear in either s1 or s2. =>difference(String s1, String s2): takes two strings and returns the string consisting of all letters that appear only in s1.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT