Difference between revisions of "CSC111 Homework 8 2018"

From dftwiki3
Jump to: navigation, search
 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:44, 1 April 2018 (EDT)
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:44, 1 April 2018 (EDT)
 
----
 
----
 +
<onlydft>
 
<br />
 
<br />
 
<bluebox>
 
<bluebox>
Line 21: Line 22:
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
# hw9_1.py
+
# hw8_1.py
 
# your name goes here
 
# your name goes here
 
# and a description of the program
 
# and a description of the program
Line 113: Line 114:
 
Document your code well, including the ''main()'',  and ''display()'' functions.  Document the class using the same approach as in Part 2, below.
 
Document your code well, including the ''main()'',  and ''display()'' functions.  Document the class using the same approach as in Part 2, below.
 
<br >
 
<br >
Store your program in a file called '''hw9_1.py''' and submit it to the Moodle HW9 PB1 section.
+
Store your program in a file called '''hw8_1.py''' and submit it to the Moodle HW8 PB1 section.
 
<br />
 
<br />
 
==Testing==
 
==Testing==
Line 168: Line 169:
 
==Preparation==
 
==Preparation==
 
<br />
 
<br />
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:
+
For this assignment, you need to create a CSV file containing some information about people and dogs.  Here's a csv file called '''peopledog.csv''' that you should store the same folder where you keep your python programs, and save the following lines in it:
 
<br />
 
<br />
 
::<source lang="text">
 
::<source lang="text">
Line 183: Line 184:
 
==The Main Program==
 
==The Main Program==
 
<br />
 
<br />
Create a new program with the code below.  Call it '''hw9_2.py'''.
+
Create a new program made of two files, one containing the class definitions, and one containing the main program.  Call the file containing the classes '''hw8_2Classes.py''' and the main program '''hw8_2.py'''.
 
<br />
 
<br />
 
::<source lang="python">
 
::<source lang="python">
# hw9_2start.py
+
# hw8_2Classes.py
# your name here
+
# your name(s) here
 
# This program maintains 2 classes, one for a person
 
# This program maintains 2 classes, one for a person
 
# and the other for a dog.  
 
# and the other for a dog.  
Line 194: Line 195:
 
# A dog is defined by a tag (its name) and a boolean indicating if it is
 
# A dog is defined by a tag (its name) and a boolean indicating if it is
 
# vaccinated or not.
 
# vaccinated or not.
# The main program outputs various lists of people.
 
#
 
  
 
class Person:
 
class Person:
Line 219: Line 218:
 
     # returns a string with the name and age.
 
     # returns a string with the name and age.
 
     def __str__( self ):
 
     def __str__( self ):
         return "{0:1}, {1:1} years old".format( self.name, self.age )
+
         return "PERSON: {0:1}, {1:1} years old".format( self.name, self.age )
  
 
     # returns the name
 
     # returns the name
Line 265: Line 264:
 
         self.tag = tag
 
         self.tag = tag
  
# readCSVFile. Reads the contents of a CSV file and return
+
</source>
# a list of strings containing all the lines.
+
<br />
 +
And here is the main program
 +
<br />
 +
::<source lang="python">
 +
# hw8_2.py
 +
# Your name(s) here
 +
# This program reads a CSV file containing information about people
 +
# and their dogs, and outputs some information about them.
 +
# Example of output:
 +
# 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
 +
#
 +
 
 +
from hw8_2Classes import *
 +
 
 
def readCSVFile( fileName ):
 
def readCSVFile( fileName ):
 +
    ''' readCSVFile.  Reads the contents of a CSV file and returns
 +
    a list of strings containing all the lines.
 +
    '''
 
     file = open( fileName, "r" )
 
     file = open( fileName, "r" )
 
     lines = file.readlines()
 
     lines = file.readlines()
Line 319: Line 340:
 
</source>
 
</source>
 
<br />
 
<br />
* Run the program.  Enter '''peopledog.csv''' when prompted for a file name.  Verify that it outputs a list of people and dogs, nicely formatted.
+
* Run the program '''hw8_2.py'''.  Enter '''peopledog.csv''' when prompted for a file name.  Verify that the program outputs a list of people and dogs, nicely formatted.
 
<br />
 
<br />
  
Line 333: Line 354:
 
* The output of the solution program for three different csv files are shown in the section below.
 
* The output of the solution program for three different csv files are shown in the section below.
 
<br />
 
<br />
Store your program in a file called ''' hw9_2.py''' and submit it to Moodle, in the HW9 PB2 section.
+
Store your program in a file called ''' hw8_2.py''' and submit it to Moodle, in the HW8 PB2 section.
 
<br />
 
<br />
 
<br />
 
<br />
Line 355: Line 376:
  
 
People without dogs:
 
People without dogs:
Joe, 23 years old, does not have a dog
+
PERSON: Joe, 23 years old, does not have a dog
Debra, 30 years old, does not have a dog
+
PERSON: Debra, 30 years old, does not have a dog
Frida, 10 years old, does not have a dog
+
PERSON: Frida, 10 years old, does not have a dog
Maria, 21 years old, does not have a dog
+
PERSON: Maria, 21 years old, does not have a dog
Millie, 25 years old, does not have a dog
+
PERSON: Millie, 25 years old, does not have a dog
  
 +
Oldest person with a dog
 
Nobody in the list has a dog.
 
Nobody in the list has a dog.
  
Line 376: Line 398:
  
 
People with unvaccinated dogs:
 
People with unvaccinated dogs:
Debra, 30 years old, has a dog: Rex (not vaccinated)
+
PERSON: Debra, 30 years old, has a dog: Rex (not vaccinated)
Millie, 25 years old, has a dog: Maxi (not vaccinated)
+
PERSON: Millie, 25 years old, has a dog: Maxi (not vaccinated)
  
 
People without dogs:
 
People without dogs:
  
Oldest: Debra, 30 years old
+
Oldest person with a dog
 
+
PERSON: Debra, 30 years old
 
------------ Example 3 ------------------
 
------------ Example 3 ------------------
 
peopledog.csv file
 
peopledog.csv file
Line 396: Line 418:
 
====================
 
====================
 
People with unvaccinated dogs:
 
People with unvaccinated dogs:
Maria, 21 years old, has a dog: Gizmo (not vaccinated)
+
PERSON: Maria, 21 years old, has a dog: Gizmo (not vaccinated)
  
 
People without dogs:
 
People without dogs:
Frank, 31 years old, does not have a dog
+
PERSON: Frank, 31 years old, does not have a dog
 
 
Oldest:  Debra, 30 years old
 
  
 +
Oldest person with a dog
 +
PERSON: Debra, 30 years old
 
</source>
 
</source>
 
<br />
 
<br />
  
 +
</onlydft>
  
</showafterdate>
 
 
<!-- =================================================================== -->
 
<!-- =================================================================== -->
 
<!-- =================================================================== -->
 
<!-- =================================================================== -->

Latest revision as of 12:44, 1 June 2018

D. Thiebaut (talk) 10:44, 1 April 2018 (EDT)



...




<showafterdate after="20180414 00:00" before="20180601 00:00">

Solution Programs


Part 1


# hw9_1sol.py
# Originally by Joyce Xue ( aa )
# (slightly edited by D. Thiebaut)
# 
#
# 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>


...