Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

[Python]For this question you will modify the processPeople () function written

ID: 3838621 • Letter: #

Question

[Python]For this question you will modify the processPeople() function written for the second assignment to handle the InvalidDate exceptions that the Person class now raises when given invalid dates. You should start from the function provided in the assignment template (which is a version written by Charley Grossman and modified by Amber Settle). The function should be modified so that when an InvalidDate exception occurs when creating an Person object the function skips that item in the file and prints a message indicating what happened. The message printed should be captured from the exception raised by the Person class. Solutions that recreate the information rather than using a proper except block to capture the information will not earn full credit. (Please ask if you don't know what I mean by this). Note that a correct solution to this function will contain no raise statements and no additional if-else statements. It should only include some additional try-except blocks.The following shows the function results on several functions provided in the assignment template zip file. The file file1.txt is the same as the one from the second assignment and contains no problematic years. The file file2.txt has some additional people in it, some of whom include invalid dates. The file file3.txt is empty. The file none.txt does not exist.

This is the ProcessPeople class followed by Persons with the Invalid Date.ProcessPeople reads a file and based on line information returns information about the Person. Person just abstracts their traits and returns information while the Invalid Date exception handles if the birthyear does not make sense.

def processPeople(f):
    '''function creates a person for every line in a given file and returns
information about them'''
   
    personList=[]
    file=open(f)
    contents=f.readlines()
  
    if os.path.getsize(f)==0:
        personList=[]
        print("Empty file.")
        return ("[]")
    else:
  
        for line in contents:
            if line.startswith('('):
                firstParenindex=line.find('(')
                lastparenindex=line.find(')')
                name=line[firstParenindex+1:lastparenindex]
                firstName=name.split(',')[0]
                lastName=name.split(',')[1]
                year=line.split(',')[2]
                person=Person.Person(firstName,lastName,year)
                personList.append(person)
                print("Person added to the list : "+person.firstName +" "+ person.lastName+" is "+ person.year+" year old!")
              
            else :
                spaceindex=line.find(',')
                line.split(str(spaceindex))
                firstName=line.split(',')[0]
                lastName=line.split(',')[1]
                year=line.split(',')[2]
                person=Person.Person(firstName,lastName,year)
                personList.append(person)
                print("Person added to the list : "+person.firstName +" "+ person.lastName+" is "+ person.year+" year old!")

class Person(object):
    'a class that abstracts a person and all of his traits'

    def __init__(self, name = 'Jane Doe', birthYear = localtime()[0]):
        self.n = name
        if birthYear > localtime()[0]:
            raise InvalidDate('{} is not a valid birth year'.format(birthYear))
        else:
            self.birthYear = birthYear
    def age(self):
        timeLst = localtime()
        return timeLst[0] - self.birthYear
    def name(self):
        return self.n
    def __repr__(self):
        return 'Person({}, {})'.format(self.n, self.birthYear)  
    def __str__(self):
        return '{} is {} years old.'.format(self.n, self.age())
    class InvalidDate(Exception):
        pass

from time import localtime
class Person(object):
    'Abstracts a person and his traits'
    def __init__(self, name, birthyear):
    class InvalidDate(Exception):
        'Handles Exceptions in person abstraction'
        pass
        self.n=name
        if birthyear > localtime()[0]:
            raise InvalidDate('{0} is not a valid birthyear '.format(birthyear))
        else:
            self.birthyear = birthyear
  
        def age(self):
            return localtime()[0] - self.birthyear
  
        def name(self):
            return self.n
  
        def __repr__(self):
            return ('Person({0} {1})'.format(self.n, self.birthyear))
  
        def __str__(self):
            return ('{0} is {1} years old'.format(self.n, self.age()))

Explanation / Answer


from time import localtime

# Question 1
class PriorityQueue(object):
    'Creates a list of objects that are sorted from least to greatest.'
  
    def __init__(self):
        emptyQue = []
        self.sortedQue = list(emptyQue)
        self.sortedQue.sort()
      
    def insert(self, item):
        self.sortedQue.append(item)
        self.sortedQue.sort()
      
    def minimum(self):
        'returns the smallest value in the que'
        return self.sortedQue[0]
  
    def removeMin(self):
        'removes the smallest value in the que'
        removed = self.sortedQue.pop(0)
        return removed
  
    def __len__(self):
        'returns the length of the que'
        return len(self.sortedQue)
  
    def __getitem__(self, index):
        'returns a value at the index given'
        return self.sortedQue[index]
  
    def __str__(self):
        'string representation of que'
        return str(self.sortedQue)
  
    def __repr__(self):
        'canonical representation of que'
        return repr(self.sortedQue)
  
    def __iter__(self):
        'iterator'
        return iter(self.sortedQue)

# Question 2
# Modify this class to include exceptions
# This must use a raise statement
# This should not use any try-except blocks
class Person(object):
    'a class representing an abstraction of a person'

    def __init__(self, name = 'Jane Doe', birthYear = localtime()[0]):
        'the constructor'
        self.n = name
        if birthYear > localtime()[0]:
            raise InvalidDate('{} is not a valid birth year'.format(birthYear))
        else:
            self.birthYear = birthYear
      
    def age(self):
        'returns the age of the person, using the local method of the time module'
        timeLst = localtime()
        return timeLst[0] - self.birthYear
      
    def name(self):
        'returns the name of the person'
        return self.n
  
    def __repr__(self):
        'gives the representation of a Person'
        return 'Person({}, {})'.format(self.n, self.birthYear)
  
    def __str__(self):
        'returns a formatted version of the Person'
        return '{} is {} years old.'.format(self.n, self.age())

# Put the InvalidDate exception class here
class InvalidDate(Exception):
    'An exception class for Person'
    pass


# Question 3
# Modify this function to handle InvalidDate exceptions
# This must use try-except blocks
# This should not use any raise statements
def processPeople(fname):
    '''Processes the file fname, creating a Person object for each line.
It prints this information as it processes it, and appends these new objects
to a list. At the end, it returns the list of Person objects.'''
    try:
        infile = open(fname, 'r')
        lst = infile.readlines()
        infile.close()
    except:
        print("The file {} could not be found. Exiting...".format(fname))
        return []
    people = []
    for line in lst:
        val = line.split()
        if len(val) > 1:
            try:
                year = int(val[1])
                nameNew = val[0].split(',')
                fullName = nameNew[1] + ' ' + nameNew[0]
                p = Person(fullName, year)
                people.append(p)
                print("Person added to the list: {}".format(p))
            except InvalidDate as Err:
                print('Item skipped in file {}: {}.'.format(fname, Err))
        else:
            try:
                nameNew = val[0].split(',')
                fullName = nameNew[1] + ' ' + nameNew[0]
                p = Person(fullName)
                people.append(p)
                print("Person added to the list: {}".format(p))
            except:
                print('Item skipped in file {}: {} is not a valid birth year.'.format(fname, year))
    return people

Except InvalidDate as e:
   Print('Item skipped in file'.format( e )

test.txt

Settle,Amber 1968
McKenzie,Chris
Settle,Cookie 2003
Settle,Djengo 2001
Fitch,Aaron

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote