Homework Solution

Error Checking and Exceptions

Problems to be Submitted (18 points)

  1. (6 points)

    def sliding(word, num=3):
        if not isinstance(word,str):
            raise TypeError('first parameter must be a string')
        if not isinstance(num,int):
            raise TypeError('second parameter must be an integer')
        if not 0 < num <= len(word):
            raise ValueError('second parameter can be at most length of first')
    


  2. (6 points)

    def pairSum(data, goal):
        if not isinstance(goal,int):
            raise TypeError('goal must be an integer')
        if not isinstance(data,list):
            raise TypeError('data must be a list')
        for val in data:
            if not isinstance(val, int):
                raise TypeError('entries of list must be integers')
    


  3. (6 points)

    def toDecimal(string, base):
        if not isinstance(base, int):
            raise TypeError('base must be integral')
        if not 2 <= base <= 10:
            raise ValueError('base must be between 2 and 10')
        if not isinstance(string, str):
            raise TypeError('value must be expressed as a string')
        if len(string) == 0:
            raise ValueError('string must be nonempty')
        for digit in string:
    	if not (digit.isdigit() and 0 <= int(digit) < base:
                raise ValueError('invalid digit for given base')
    


Extra Credit

  1. (2 points)

    def toDecimal(string, base):
        if not isinstance(base, int):
            raise TypeError('base must be integral')
        if not 2 <= base <= 36:
            raise ValueError('base must be between 2 and 36')
        if not isinstance(string, str):
            raise TypeError('value must be expressed as a string')
        if len(string) == 0:
            raise ValueError('string must be nonempty')
        for digit in string:
            if digit.isdigit():
                if not 0 <= int(digit) < base:
                    raise ValueError('invalid digit for given base')
            else:
                if not 10 <= (ord(digit) - ord('A')) < base:
                    raise ValueError('invalid digit for given base')
    

Last modified: Friday, 13 October 2017