Difference between revisions of "CSC111 Homework 9 2015"

From dftwiki3
Jump to: navigation, search
Line 22: Line 22:
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
 +
# hw9_1.py
 +
# your name goes here
 +
# and a description of the program
 +
 +
 
#
 
#
 
# missing class goes here...
 
# missing class goes here...
 
#
 
#
 +
  
 
def getNewCat():
 
def getNewCat():
Line 51: Line 57:
 
     #        Garfield, 4, Yes, Yes, Orange Tabby"""
 
     #        Garfield, 4, Yes, Yes, Orange Tabby"""
  
     file = open( "cats.csv", "r" )
+
     file = open( "cats1.csv", "r" )
 
     text = file.read()
 
     text = file.read()
 
     file.close()
 
     file.close()
Line 88: Line 94:
 
</source>
 
</source>
 
<br />
 
<br />
==Example cats.csv File ==
+
==Example cats1.csv File ==
 +
<br />
 +
Here is an example of the format of the csv file.
 
<br />
 
<br />
 
::<source lang="text">
 
::<source lang="text">

Revision as of 07:19, 31 March 2015

--D. Thiebaut (talk) 22:47, 30 March 2015 (EDT)



<showafterdate after="20150402 16:00" before="20150601 00:00">

This assignment is due the evening of Tuesday 4/7/15, at 11:55 p.m. You will be able to evaluate Problem 1, but not Problem 2.







Problem #1: Lost Cat

(image from nicepixy.net)

Cats.jpg


The program below is missing its class! And it is also missing its documentation! It used to contain a class defined, with methods and member variables, and a fully developped documentation, but unfortunately all of them got erased.

We do have the output of a run of the program, though, when it still had its class definition. Both the incomplete code and the output are shown below.


# hw9_1.py
# your name goes here
# and a description of the program


#
# missing class goes here...
#


def getNewCat():
    print( "\nPlease enter the information for the new cat:")
    name = input(       "Cat name?         " )
    age  = int( input(  "Age, in years?    " ) )
    vac  = input(       "Vaccinated (Y/N)? " ).strip().lower()
    vac  = vac in ['y', 'yes']
    neut = input(       "Neutered (Y/N)?   " ).strip().lower()
    neut = neut in ['y', 'yes' ]
    breed= input(       "Breed?            " ).strip()
    
    return Cat( name, age, vac, neut, breed )

def display( catList, caption ):
    print( "\n\n"+caption )
    print( "=" * len( caption ) )
    for cat in catList:
        print( cat )

def main():
    #comments below are for debugging purpose
    #text="""Minou, 3, Yes, Yes, stray
    #       Max, 1, Yes, No, Burmese
    #        Gizmo, 2, No, No, Bengal
    #        Garfield, 4, Yes, Yes, Orange Tabby"""

    file = open( "cats1.csv", "r" )
    text = file.read()
    file.close()

    for line in text.split( "\n" ):
        words = line.strip().split( "," )
        if len( words ) != 5:
            continue
        name, age, vaccinated, neutered, breed = words
        age = int( age.strip() )
        if vaccinated.strip().lower() == "yes":
            vaccinated = True
        else:
            vaccinated = False

        neutered = neutered.strip().lower() == "yes"
        
        cat = Cat( name.strip(), age, vaccinated, neutered, breed.strip() )
        try:
            cats.append( cat )
        except NameError:
            cats = []
            cats.append( cat )

    display( cats, "List of cats:" )

    vaccinatedNeuteredCats = []
    for cat in cats:
        if cat.isVaccinated() and cat.isNeutered():
            vaccinatedNeuteredCats.append( cat )

    display( vaccinatedNeuteredCats, "Vaccinated and neutered cats:" )
    
    
main()


Example cats1.csv File


Here is an example of the format of the csv file.

Minou, 3, Yes, Yes, stray
Max, 1, Yes, No, Burmese
Gizmo, 2, No, No, Bengal
Garfield, 4, Yes, Yes, Orange Tabby


Corresponding Output


List of cats:
=============
Cat: Minou, age: 3, vaccinated, neutered (stray)
Cat: Max, age: 1, vaccinated, not neutered (Burmese)
Cat: Gizmo, age: 2, not vaccinated, not neutered (Bengal)
Cat: Garfield, age: 4, vaccinated, neutered (Orange Tabby)

Vaccinated and neutered cats:
=============================
Cat: Minou, age: 3, vaccinated, neutered (stray)
Cat: Garfield, age: 4, vaccinated, neutered (Orange Tabby)


Question

Recreate the original program with its Cat class. Make sure that it will generate the same output shown above if fed the same cat information.

Document your code well, including the main(), getNewCat() and display() functions. Document the class using the same approach as in Part 2, below.
Store your program in a file called hw9_1.py and submit it to the Moodle HW9 PB1 section.




Problem #2: Of dogs and people...

PersonAndDog.jpg

(image from naturesmightypictures.blogspot.com)

Preparation


For this assignment, you need to create a CSV file containing some information about people and dogs. Create a csv file called peopledog.csv in the same folder where you keep your python programs, and save the following lines in it:

Joe, 23, Fido, vaccinated
Debra, 30, Rex, not vaccinated
Frida, 10, Ralph, vaccinated
Maria, 21, Gizmo, vaccinated
Frank, 31, ,
Millie, 25, Maxi, not vaccinated


  • The information above contains the name and age of people, and the name of their dog, as well as its vaccinated status, if they own a dog. If they do not own a dog, then their age is followed by two empty strings (see Frank above).


The Main Program


Create a new program with the code below. Call it hw9_2.py.

# hw9_2start.py
# your name here
# This program maintains 2 classes, one for a person
# and the other for a dog. 
# A person object is defined by a name, an age, and a dog.
# If a person does not own a dog, then that person's dog field is set to None.
# A dog is defined by a tag (its name) and a boolean indicating if it is
# vaccinated or not.
# The main program outputs various lists of people.
#

class Person:
    # a class containing 4 private member variables:
    # - name of the person (string)
    # - age (integer)
    # - gpa (float)
    # - major (string, uppercase)
    # methods:
    # getName(): returns the name of the person (string)
    # getAge(): returns the age of the person (int)
    # setAge(x): sets the age of the person to x (int)

    # constructor: intializes a person with all fields
    def __init__(self, n, a, dg ):
        self.name = n
        self.age  = a
        self.dog  = dg

    def getDog( self ):
        return self.dog
    
    # returns a string with the name and age.
    def __str__( self ):
        return "{0:1}, {1:1} years old".format( self.name, self.age )

    # returns the name
    def getName( self ):
        return self.name

    # set the age to a new value x
    def setAge( self, x ):
        self.age = x

    # returns the age of the person
    def getAge( self ):
        return self.age


class Dog:
    # a class containing 2 private member variables:
    # - name-tag of the dog (string)
    # - whether the dog is vaccinated or not (boolean)
    # methods:
    # isVaccinated(): returns True if the dog is vaccinated, False otherwise
    # getName(): returns the name-tag of the dog
    # setName(x): sets the name-tag of the dog
    # constructor
    def __init__( self, tag, vaccinated ):
        self.tag = tag
        self.vaccinated = vaccinated

    # default string representation for the dog
    def __str__( self ):
        if self.vaccinated==True:
            return "{0:1} (vaccinated)".format( self.tag )
        return "{0:1} (not vaccinated)".format( self.tag )

    # isVaccinated: returns True if the dog is vaccinated, False otherwise
    def isVaccinated( self ):
        return self.vaccinated

    # returns the name of the dog
    def getNameTag( self ):
        return self.tag

    # changes the name-tag 
    def setNameTag( self, tag ):
        self.tag = tag

# readCSVFile.  Reads the contents of a CSV file and return
# a list of strings containing all the lines.
def readCSVFile( fileName ):
    file = open( fileName, "r" )
    lines = file.readlines()
    file.close()
    return lines

         
# ================================================
#                     main
# ================================================
def main():
    # get the contents of the file
    lines = readCSVFile( "peopledog.csv" )
    
    # create a list of people, and their dog (if they own one)
    people = []
    
    # parse the text and add it as people-dog pairs in the list
    for line in lines:
        
        # reject lines that are not formatted correctly
        if len( line.split(',') ) != 4:
            continue

        # parse line
        name, age, tag, vacc = line.split(',')
        name = name.strip()
        age  = int( age.strip() )
        tag  = tag.strip()
        vacc = "not" not in vacc.lower()

        if len( tag )==0:
            p = Person(name, age, None  )
        else:
            p = Person(name, age, Dog( tag, vacc ) )

        # add this new person to the list
        people.append( p )

        
    # Display the list
    for person in people:
        
        if person.getDog() != None:
            print( person, ", has a dog: ", person.getDog(), sep="" )
        else:
            print( person, ", does not have a dog", sep="" )

main()


  • Run the program. Verify that it outputs a list of people and dogs, nicely formatted.


Your Assignment


  • Modify the main program only (not the classes), so that your new program will output:
    1. the list of people who have unvaccinated dogs
    2. the list of people without dogs
    3. the oldest person who has a dog


  • Your output should match exactly the output of the solution program, so play close attention to the formatting of your output.
  • The output of the solution program for the csv file you created at the beginning of this problem is shown below:


Joe, 23 years old, has a dog: Fido (vaccinated)
Debra, 30 years old, has a dog: Rex (not vaccinated)
Frida, 10 years old, has a dog: Ralph (vaccinated)
Maria, 21 years old, has a dog: Gizmo (vaccinated)
Frank, 31 years old, does not have a dog
Millie, 25 years old, has a dog: Maxi (not vaccinated)

Debra, 30 years old, has a an unvaccinated dog: Rex
Millie, 25 years old, has a an unvaccinated dog: Maxi

Frank, 31 years old, does not have a dog.

Debra, 30 years old, is the oldest person owning a dog.


  • If the CSV file had contained only people who didn't own dogs, the last line of the output would have read:


Nobody in the list has dogs.



Store your program in a file called hw9_2.py and submit it to Moodle, in the HW9 PB2 section.




</showafterdate>

<showafterdate after="20150408 00:00" before="20150601 00:00">

Solution Programs


Part 1




Part 2


# hw9_2sol.py
# D. Thiebaut
# This program maintains 2 classes, one for a person
# and the other for a dog. 
# A person object is defined by a name, an age, and a dog.
# If a person does not own a dog, then that person's dog field is set to None.
# A dog is defined by a tag (its name) and a boolean indicating if it is
# vaccinated or not.
# The main program outputs various lists of people.
#

class Person:
    # a class containing 4 private member variables:
    # - name of the person (string)
    # - age (integer)
    # - gpa (float)
    # - major (string, uppercase)
    # methods:
    # getName(): returns the name of the person (string)
    # getAge(): returns the age of the person (int)
    # setAge(x): sets the age of the person to x (int)

    # constructor: intializes a person with all fields
    def __init__(self, n, a, dg ):
        self.name = n
        self.age  = a
        self.dog  = dg

    def getDog( self ):
        return self.dog
    
    # returns a string with the name and age.
    def __str__( self ):
        return "{0:1}, {1:1} years old".format( self.name, self.age )

    # returns the name
    def getName( self ):
        return self.name

    # set the age to a new value x
    def setAge( self, x ):
        self.age = x

    # returns the age of the person
    def getAge( self ):
        return self.age


class Dog:
    # a class containing 2 private member variables:
    # - name-tag of the dog (string)
    # - whether the dog is vaccinated or not (boolean)
    # methods:
    # isVaccinated(): returns True if the dog is vaccinated, False otherwise
    # getName(): returns the name-tag of the dog
    # setName(x): sets the name-tag of the dog
    # constructor
    def __init__( self, tag, vaccinated ):
        self.tag = tag
        self.vaccinated = vaccinated

    # default string representation for the dog
    def __str__( self ):
        if self.vaccinated==True:
            return "{0:1} (vaccinated)".format( self.tag )
        return "{0:1} (not vaccinated)".format( self.tag )

    # isVaccinated: returns True if the dog is vaccinated, False otherwise
    def isVaccinated( self ):
        return self.vaccinated

    # returns the name of the dog
    def getNameTag( self ):
        return self.tag

    # changes the name-tag 
    def setNameTag( self, tag ):
        self.tag = tag

# readCSVFile.  Reads the contents of a CSV file and return
# a list of strings containing all the lines.
def readCSVFile( fileName ):
    file = open( fileName, "r" )
    lines = file.readlines()
    file.close()
    return lines

# ================================================
#                     main
# ================================================
def main():
    # get the contents of the file
    lines = readCSVFile( "peopledog.csv" )
    
    # create a list of people, and their dog (if they own one)
    people = []
    
    # parse the text and add it as people-dog pairs in the list
    for line in lines:
        if len( line.split(',') ) != 4:
            continue
        name, age, tag, vacc = line.split(',')
        name = name.strip()
        age  = int( age.strip() )
        tag  = tag.strip()
        vacc = "not" not in vacc.lower()

        if len( tag )==0:
            p = Person(name, age, None  )
        else:
            p = Person(name, age, Dog( tag, vacc ) )

        # add this new person to the list
        people.append( p )

        
    # Display the whole list
    for person in people:        
        if person.getDog() != None:
            print( person, ", has a dog: ", person.getDog(), sep="" )
        else:
            print( person, ", does not have a dog", sep="" )

    print()
    
    # display the list of people with unvaccinated dogs
    for person in people:        
        dog = person.getDog()
        if dog != None and dog.isVaccinated()==False:
            print( person, ", has a an unvaccinated dog: ",
                   person.getDog().getNameTag(), sep="" )
            

    print()

    # display the list of people without dogs
    for person in people:        
        dog = person.getDog()
        if dog == None:
            print( person, ", does not have a dog.", sep="" )

    print()

    # display the oldest person with a dog
    oldestAge = 0
    oldestIndex = -1
    for i in range( len( people ) ):
        person = people[i]
        if person.getAge() > oldestAge and person.getDog() != None:
            oldestAge = person.getAge()
            oldestIndex = i

    if oldestIndex == -1:
        print( "Nobody in the list has dogs." )
    else:
        person = people[oldestIndex]
        print( person, ", is the oldest person owning a dog.", sep="" )
    
    
main()


</showafterdate>