Difference between revisions of "CSC111 Homework 9 2015b"

From dftwiki3
Jump to: navigation, search
 
(2 intermediate revisions by the same user not shown)
Line 77: Line 77:
 
     display( vaccinatedNeuteredCats, "Vaccinated and neutered cats:" )
 
     display( vaccinatedNeuteredCats, "Vaccinated and neutered cats:" )
 
      
 
      
if __name__=="__main__":
+
main()
      main()
 
  
 
</source>
 
</source>
Line 281: Line 280:
 
def main():
 
def main():
 
     # get the contents of the file
 
     # get the contents of the file
     lines = readCSVFile( "peopledog.csv" )
+
     lines = readCSVFile( input( "File name? " ) )
 +
    print()
 
      
 
      
 
     # create a list of people, and their dog (if they own one)
 
     # create a list of people, and their dog (if they own one)
Line 320: Line 320:
 
</source>
 
</source>
 
<br />
 
<br />
* Run the program.  Verify that it outputs a list of people and dogs, nicely formatted.
+
* Run the program.  Enter '''peopledog.csv''' when prompted for a file name.  Verify that it outputs a list of people and dogs, nicely formatted.
 
<br />
 
<br />
  

Latest revision as of 11:43, 12 November 2015

--D. Thiebaut (talk) 15:25, 1 November 2015 (EST)



<showafterdate after="20151105 12:00" before="20151231 00:00">

This assignment is due the evening of Thursday 11/12/15, at 11:55 p.m.







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 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( input("Enter filename: "), "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. You cannot modify the main program!. Make sure that your program with the reconstituted class generates the same output as the one shown above, when fed the same CSV file.

Document your code well, including the main(), 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.

Testing


Your program will be tested using your Cat class, and the main() function shown in the code above. Whatever modification you bring to your main function will not be used. For this reason, make sure you do not modify the code of the main() function that is given to you.




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( input( "File name? " ) )
    print()
    
    # 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. Enter peopledog.csv when prompted for a file name. 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, and if nobody has a dog, just a sentence that indicates that nobody 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 three different csv files are shown in the section below.


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

Example Outputs for Different CSV Files (added 4/4/15)


------------ Example 1 ------------------
peopledog.csv file
===========

Joe, 23, ,
Debra, 30, ,
Frida, 10, ,
Maria, 21, ,
Millie, 25, ,

Output of the Solution Program
====================

People with unvaccinated dogs:

People without dogs:
Joe, 23 years old, does not have a dog
Debra, 30 years old, does not have a dog
Frida, 10 years old, does not have a dog
Maria, 21 years old, does not have a dog
Millie, 25 years old, does not have a dog

Nobody in the list has a dog.

------------ Example 2 ------------------
peopledog.csv file
===========
Joe, 23, Fido, vaccinated
Debra, 30, Rex, not vaccinated
Frida, 10, Ralph, vaccinated
Maria, 21, Gizmo, vaccinated
Millie, 25, Maxi, not vaccinated

Output of the Solution Program
====================

People with unvaccinated dogs:
Debra, 30 years old, has a dog: Rex (not vaccinated)
Millie, 25 years old, has a dog: Maxi (not vaccinated)

People without dogs:

Oldest:  Debra, 30 years old

------------ Example 3 ------------------
peopledog.csv file
===========
Joe, 23, Fido, vaccinated
Debra, 30, Rex,  vaccinated
Frida, 10, Ralph, vaccinated
Maria, 21, Gizmo, not vaccinated
Frank, 31, ,
Millie, 25, Maxi,  vaccinated

Output of the Solution Program
====================
People with unvaccinated dogs:
Maria, 21 years old, has a dog: Gizmo (not vaccinated)

People without dogs:
Frank, 31 years old, does not have a dog

Oldest:  Debra, 30 years old



</showafterdate>

<showafterdate after="20151113 00:00" before="20151231 00:00">

Solution Programs


Part 1


# hw9_1sol.py
# Originally by Joyce Xue ( aa )
# (slightly edited by D. Thiebaut)
# 04.15.2014
#
# This program contains a class Cat that describe a cat with its name, age,
# being vaccinated or not, being neutered or not and breed
#
# To create an object of this type, simply use the constructor, as follows:
#
#        cat = Cat(name, age, vaccinated, neutered, breed)
#
# The methods supported are:
#
# isVaccinated(): returns if the cat is vaccinated
#
# isNeutered(): returns the  name of the planet with the largest diameter
#
# __str__(): convert the object to a string
# ------------------------------------------------------------------------------------------------------
class Cat:
    # contructor. Initialize all memebers.
    def __init__( self,name, age, vaccinated, neutered, breed):
        self._name=name
        self._age=age
        self._vac=vaccinated
        self._neu=neutered
        self._breed=breed

    #==================================================================
    # __str__() : When call print(cat), this function
    #                      automatically converts the cat to a string
    #==================================================================
    def __str__(self):
        # make up the return string by following the required format
        temp = "Cat: "+self._name+","+" age: "+str(self._age)+", "

        # convert boolean value to string
        if self._vac: temp=temp+"vaccinated, "
        else: temp=temp+"not vaccinated, "

        if self._neu: temp=temp+"neutered "
        else: temp=temp+"not neutered "

        temp=temp+"("+self._breed+")"
        
        return temp

    #==================================================================
    # isVaccinated(): return if the cat is vaccinated
    #==================================================================
    def isVaccinated(self):
        return self._vac

    #==================================================================
    # isNeutered(): return if the cat is neutered
    #==================================================================
    def isNeutered(self):
        return self._neu


#==================================================================
# getNewCat(): ask for user input to create a new
#                       cat and return it
#==================================================================
def getNewCat():
    # user input for name, age, if vaccinated, if neutered and breed
    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 )

#==================================================================
# display(): print each cat in a Cat collection
# L       - a list of cats
# caption - the subject of the list to be printed
#==================================================================
def display( L, caption ):
    # print the subject
    print( "\n\n"+caption )
    print( "=" * len( caption ) )
    # go over the list and print each cat's info
    for cat in L:
        print( cat )

#==================================================================
# main(): 
#  * creates a list of cat objects, displays it.
# 
#==================================================================
def main():
    # get the contents of cats.csv
    file = open( "cats2.csv", "r" )
    text = file.read()
    file.close()
    
    # use the text as the initial data, generate cats
    for line in text.split( "\n" ):
        # split each line into items
        words = line.strip().split( "," )
        # if data is not exactly 5, skip
        if len( words ) != 5:
            continue
        
        # set items to variables
        name, age, vaccinated, neutered, breed = words
        # convert age to int
        age = int( age.strip() )
        # convert user inputs to booleans
        if vaccinated.strip().lower() == "yes":
            vaccinated = True
        else:
            vaccinated = False

        neutered = neutered.strip().lower() == "yes"

        # construct a cat
        cat = Cat( name.strip(), age, vaccinated, neutered, breed.strip() )

        try:
            # add the cat to the list
            cats.append( cat )
        except NameError:
            # if the cats list is not initialized, initialize it and append the first cat
            cats = []
            cats.append( cat )

    # output the cat list
    display( cats, "List of cats:" )


    # Go through each cat and add those who is both vaccinated and neutered into a list
    vaccinatedNeuteredCats = []
    for cat in cats:
        if cat.isVaccinated() and cat.isNeutered():
            vaccinatedNeuteredCats.append( cat )

    # output the cats in this new list (both vaccinated and neutered)
    display( vaccinatedNeuteredCats, "Vaccinated and neutered cats:" )

    
# Main entry point for the program
main()


Part 2


# 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="" )

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

    print()

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

    print()

    # display the oldest person who has a dog
    oldest = None
    oldestAge = 0
    for person in people:
        if person.getAge() > oldestAge:
            oldestAge = person.getAge()
            oldest = person

    if oldest.getDog()==None:
        print( "Nobody in the list has dogs." )
    else:
        print( oldest, ", is the oldest person owning a dog." )

main()


</showafterdate>


...