Difference between revisions of "CSC111 Homework 10 2014"

From dftwiki3
Jump to: navigation, search
(Problem #1)
(Problem #2: Of dogs and people...)
 
(36 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:30, 8 April 2014 (EDT)
 
--[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:30, 8 April 2014 (EDT)
 
----
 
----
<center> <font size="+2">Page under construction!</font> </center> <P> <center> [[File:UnderConstruction.jpg|300px]] </center>
 
 
=Problem #1=
 
 
<br />
 
<br />
The program below is missing its class!  And it is also missing its documentation!  It used to have a class defined, with methods and member variables, and superbly useful documentation, but unfortunately all of them got erased.
+
<bluebox>
 +
This assignment is due the evening of Thursday  4/17/14 at midnight.  You can work on this assignment in pair.
 +
</bluebox>
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
=Problem #1: Lost Cat=
 +
(image from [http://nicepixy.net/wp-content/uploads/2013/08/funny-cartoons-42.jpg nicepixy.net])
 +
[[Image:cats.jpg|right|200px]]
 +
<br />
 +
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.
 
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.
  
 
<br />
 
<br />
<source lang="python">def getNewCat():
+
<source lang="python">
 +
#
 +
# missing class goes here...
 +
#
 +
 
 +
 
 +
 
 +
def getNewCat():
 
     print( "\nPlease enter the information for the new cat:")
 
     print( "\nPlease enter the information for the new cat:")
 
     name = input(      "Cat name?        " )
 
     name = input(      "Cat name?        " )
Line 21: Line 38:
 
      
 
      
 
     return Cat( name, age, vac, neut, breed )
 
     return Cat( name, age, vac, neut, breed )
 +
 +
def display( L, caption ):
 +
    print( "\n\n"+caption )
 +
    print( "=" * len( caption ) )
 +
    for cat in L:
 +
        print( cat )
  
 
def main():
 
def main():
Line 39: Line 62:
 
             vaccinated = False
 
             vaccinated = False
  
         if neutered.strip().lower() == "yes":
+
         neutered = neutered.strip().lower() == "yes"
            neutered = True
 
        else:
 
            neutered = False
 
 
          
 
          
 
         cat = Cat( name.strip(), age, vaccinated, neutered, breed.strip() )
 
         cat = Cat( name.strip(), age, vaccinated, neutered, breed.strip() )
Line 62: Line 82:
 
             vaccinatedNeuteredCats.append( cat )
 
             vaccinatedNeuteredCats.append( cat )
  
     display( vaccinatedNeuteredCats, "Vaccinated and neutered cats" )
+
     display( vaccinatedNeuteredCats, "Vaccinated and neutered cats:" )
 
      
 
      
 
      
 
      
 
main()
 
main()
 
</source>
 
</source>
 
+
<br />
 
==Output==
 
==Output==
 
<br />
 
<br />
Line 95: Line 115:
  
  
Vaccinated and neutered cats
+
Vaccinated and neutered cats:
============================
+
=============================
 
Cat: Minou, age: 3, vaccinated, neutered (stray)
 
Cat: Minou, age: 3, vaccinated, neutered (stray)
 
Cat: Garfield, age: 4, vaccinated, neutered (Orange Tabby)
 
Cat: Garfield, age: 4, vaccinated, neutered (Orange Tabby)
Line 104: Line 124:
 
<br />
 
<br />
 
;Question  
 
;Question  
Recreate the original program with its Cat class.  Make sure that it will generate the same output show above if fed the same cat information illustrated in the output, also shown above.
+
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 this file: [[CSC111 Lab 10 Addendum 2014| Planets.py]].
 +
<br >
 +
Store your program in a file called ''' hw10a.py''' and submit it [http://cs.smith.edu/~thiebaut/111b/submit10.php here].
 +
<br />
 +
<!--
 +
=Problem #2=
 +
<br />
 +
This problem was originally part of [[CSC111_Lab_10_2014| Lab #10]].
 +
<br />
 +
Copy the code in this [[CSC111 Lab 10 Addendum 2014| page]] and store it in a new Python file called '''Planets.py'''.  Save it in your current working directory (where your other Python programs are).
 +
 
 +
Create a new program called '''hw10b.py''' and add the code below to it.
 +
<br />
 +
<source lang="python">
 +
from Planets import PlanetList
 +
 
 +
def playWithPlanets():
 +
    planets = PlanetList()
 +
    print( planets )
  
Store your program in a file called ''' hw10a.py''' and submit it [http://cs.smith.edu/~thiebaut/111b/submit10.php| here]
+
 
 +
def main():
 +
    playWithPlanets()
 +
 
 +
main()
 +
</source>
 +
<br />
 +
* Run your program to see how it behaves.
 +
* Study the class '''PlanetList''', and figure out how each method works.
 +
<br />
 +
==Your assignment==
 +
<br />
 +
* Add code to your hw10b.py program so that it will
 +
*# display the name of the smallest planet
 +
*# display the name of the largest planet
 +
*# display the number of planets
 +
*# get the user to input a new planet that will be added to the list of planets (this [http://sciencenetlinks.com/interactives/messenger/psc/PlanetSize.html page] has good information on planets)
 +
*# display the new list of names of planets
 +
<br />
 +
::'''NOTE: you cannot modify the code inside the class!'''
 +
<br />
 +
Store your program in a file called ''' hw10b.py''' and submit it [http://cs.smith.edu/~thiebaut/111b/submit10.php here].
 +
<br />
 +
-->
 +
 
 +
<br /><br /><br />
 +
 
 +
=Problem #2: Of dogs and people...=
 +
[[Image:PersonAndDog.jpg|200px|right]]
 +
(image from [http://naturesmightypictures.blogspot.com/2006/10/people-and-dogs.html naturesmightypictures.blogspot.com])
 +
<br />
 +
<br />
 +
Create a new program with the code below.  Call it '''hw10b.py'''.
 +
<br />
 +
<source lang="python">
 +
#
 +
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 ):
 +
        self._name = n
 +
        self._age  = a
 +
 
 +
    # returns a string with the name and age.
 +
    def __str__( self ):
 +
        return "%s, %d years old" % ( 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 "%s (vaccinated)" % self._tag
 +
        return "%s (not vaccinated)" % 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
 +
 
 +
 
 +
class ListPeopleDog:
 +
    # a class that maintains a list of pairs.  The first
 +
    # element of a pair is a Person object, the second a Dog object
 +
    # if the person doesn't have a dog, the second element of the pair is None
 +
    # Methods supported:
 +
    # isEmpty(): returns True if the list is empty, False othewise
 +
    # append( p, d ): appends a pair( person, dog) to the list
 +
    # getDogOf( name ): returns the dog object associated with the given person's name
 +
    # getOwnerOf( tag ): returns the person object associated with the given dog tag
 +
    # size( ): returns the number of pairs in the list
 +
    # getPersonDogAt( i ): returns the person object and the dog object located
 +
    # at Index i in the list.
 +
 
 +
    # constructor
 +
    def __init__( self ):
 +
        self._L = []
 +
 
 +
    # returns a string formatted as several lines, each representing
 +
    # a person and his/her dog.
 +
    def __str__( self ):
 +
        s = ""
 +
        for person, dog in self._L:
 +
            if dog==None:
 +
                s = s + str( person )+ " [No dogs]\n"
 +
            else:
 +
                s = s + str( person )+ " ["+str( dog ) +"]\n"
 +
        return s
 +
   
 +
    # returns True if the list is empty.  False otherwise.
 +
    def isEmpty( self ):
 +
        return len( self._L )==0
 +
 
 +
    # add a new pair to the list
 +
    def append( self, person, dog ):
 +
        self._L.append( (person, dog) )
 +
 
 +
    # returns the dog associated with the first person who's name is passed.
 +
    def getDogOf( self, name ):
 +
        name = name.strip().lower()
 +
        for person, dog in self._L:
 +
            if dog==None:
 +
                continue
 +
            if person.getName().lower() == name:
 +
                return dog
 +
        return None
 +
 
 +
    # returns the person object associated with the first dog in the list with the
 +
    # tag passed as a parameter.
 +
    def getOwnerOf( self, name ):
 +
        name = name.strip().lower()
 +
        for person, dog in self._L:
 +
            if dog==None:
 +
                continue
 +
            if dog.getNameTag().lower()==name:
 +
                return person
 +
        return None
 +
 +
    # returns the number of pairs in the list.
 +
    def size( self ):
 +
        return len( self._L )
 +
 
 +
    # returns the person and dog located at Index i in the list.
 +
    def getPersonDogAt( self, i ):
 +
        if i < len( self._L ):
 +
            return self._L[i][0], self._L[i][1]
 +
        return None, None
 +
       
 +
# ================================================
 +
#                    main
 +
# ================================================
 +
def main():
 +
    text = """Joe, 23, Fido, vaccinated
 +
              Debra, 30, Rex, not vaccinated
 +
              Frida, 10, Ralph, vaccinated
 +
              Maria, 21, Gizmo, vaccinated
 +
              Frank, 31, ,
 +
              Millie, 25, Maxi, not vaccinated"""
 +
   
 +
    # create a new ListPeopleDog object   
 +
    L = ListPeopleDog()
 +
   
 +
    # parse the text and add it as people-dog pairs in the list
 +
    for line in text.split( "\n" ):
 +
        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:
 +
            L.append( Person(name, age), None  )
 +
        else:
 +
            L.append( Person(name, age), Dog( tag, vacc )  )
 +
 
 +
    # Display the list
 +
    for i in range( L.size() ):
 +
        p, d = L.getPersonDogAt( i )
 +
        if d != None:
 +
            print( p, "has a dog: ", d )
 +
        else:
 +
            print( p, "does not have a dog" )
 +
 
 +
main()
 +
</source>
 +
<br />
 +
==Your Assignment==
 +
<br />
 +
* Without modifying any of the classes, make your program output
 +
*# the list of people who have unvaccinated dogs
 +
*# the list of people without dogs
 +
*# the oldest person who has a dog
 +
 
 +
<br />
 +
An example of the output of the solution program is shown below:
 +
<br />
 +
<source lang="text">
 +
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 non vaccinated dog called Rex
 +
Millie, 25 years old has a non vaccinated dog called Maxi
 +
 
 +
Frank, 31 years old doesn't have a dog
 +
 
 +
The oldest person to own a dog is Debra, 30 years old and the dog is Rex (not vaccinated)
 +
</source>
 +
<br />
 +
Store your program in a file called ''' hw10b.py''' and submit it [http://cs.smith.edu/~thiebaut/111b/submit10.php  here].
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
'''Note:  Solutions of the type shown below will be given negative points...'''
 +
<br />
 +
<source lang="python">
 +
print( "Debra, 30 years old has a non vaccinated dog called Rex" )
 +
print( "Millie, 25 years old has a non vaccinated dog called Maxi" )
 +
print()
 +
print( "Frank, 31 years old doesn't have a dog" )
 +
print()
 +
print( "The oldest person to own a dog is Debra, 30 "
 +
          +"years old and the dog is Rex (not vaccinated)")
 +
print()
 +
</source>
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
<br />
 +
[[Category:CSC111]][[Category:Python]][[Category:Homework]]

Latest revision as of 22:51, 16 April 2014

--D. Thiebaut (talk) 10:30, 8 April 2014 (EDT)



This assignment is due the evening of Thursday 4/17/14 at midnight. You can work on this assignment in pair.







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.


#
# 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( L, caption ):
    print( "\n\n"+caption )
    print( "=" * len( caption ) )
    for cat in L:
        print( cat )

def main():
    text="""Minou, 3, Yes, Yes, stray
            Max, 1, Yes, No, Burmese
            Gizmo, 2, No, No, Bengal
            Garfield, 4, Yes, Yes, Orange Tabby"""

    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:" )

    cats.append( getNewCat() )

    display( cats, "List of cats with new addition:" )

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

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


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)

Please enter the information for the new cat:
Cat name?         Ralph
Age, in years?    4
Vaccinated (Y/N)? y
Neutered (Y/N)?   y
Breed?            Angora


List of cats with new addition:
===============================
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)
Cat: Ralph, age: 4, vaccinated, neutered (Angora)


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


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 this file: Planets.py.
Store your program in a file called hw10a.py and submit it here.




Problem #2: Of dogs and people...

PersonAndDog.jpg

(image from naturesmightypictures.blogspot.com)

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

# 
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 ):
        self._name = n
        self._age  = a

    # returns a string with the name and age.
    def __str__( self ):
        return "%s, %d years old" % ( 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 "%s (vaccinated)" % self._tag
        return "%s (not vaccinated)" % 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


class ListPeopleDog:
    # a class that maintains a list of pairs.  The first
    # element of a pair is a Person object, the second a Dog object
    # if the person doesn't have a dog, the second element of the pair is None
    # Methods supported:
    # isEmpty(): returns True if the list is empty, False othewise
    # append( p, d ): appends a pair( person, dog) to the list
    # getDogOf( name ): returns the dog object associated with the given person's name
    # getOwnerOf( tag ): returns the person object associated with the given dog tag
    # size( ): returns the number of pairs in the list
    # getPersonDogAt( i ): returns the person object and the dog object located 
    # at Index i in the list.

    # constructor
    def __init__( self ):
        self._L = []

    # returns a string formatted as several lines, each representing
    # a person and his/her dog.
    def __str__( self ):
        s = ""
        for person, dog in self._L:
            if dog==None:
                s = s + str( person )+ " [No dogs]\n"
            else:
                s = s + str( person )+ " ["+str( dog ) +"]\n"
        return s
    
    # returns True if the list is empty.  False otherwise.
    def isEmpty( self ):
        return len( self._L )==0

    # add a new pair to the list
    def append( self, person, dog ):
        self._L.append( (person, dog) )

    # returns the dog associated with the first person who's name is passed.
    def getDogOf( self, name ):
        name = name.strip().lower()
        for person, dog in self._L:
            if dog==None:
                continue
            if person.getName().lower() == name:
                return dog
        return None

    # returns the person object associated with the first dog in the list with the
    # tag passed as a parameter.
    def getOwnerOf( self, name ):
        name = name.strip().lower()
        for person, dog in self._L:
            if dog==None:
                continue
            if dog.getNameTag().lower()==name:
                return person
        return None
 
    # returns the number of pairs in the list.
    def size( self ):
        return len( self._L )

    # returns the person and dog located at Index i in the list.
    def getPersonDogAt( self, i ):
        if i < len( self._L ):
            return self._L[i][0], self._L[i][1]
        return None, None
        
# ================================================
#                     main
# ================================================
def main():
    text = """Joe, 23, Fido, vaccinated
              Debra, 30, Rex, not vaccinated
              Frida, 10, Ralph, vaccinated
              Maria, 21, Gizmo, vaccinated
              Frank, 31, ,
              Millie, 25, Maxi, not vaccinated"""
    
    # create a new ListPeopleDog object    
    L = ListPeopleDog()
    
    # parse the text and add it as people-dog pairs in the list
    for line in text.split( "\n" ):
        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:
            L.append( Person(name, age), None  )
        else:
            L.append( Person(name, age), Dog( tag, vacc )  )

    # Display the list
    for i in range( L.size() ):
        p, d = L.getPersonDogAt( i )
        if d != None:
            print( p, "has a dog: ", d )
        else:
            print( p, "does not have a dog" )

main()


Your Assignment


  • Without modifying any of the classes, make your program 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


An example of the output of the solution program 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 non vaccinated dog called Rex
Millie, 25 years old has a non vaccinated dog called Maxi

Frank, 31 years old doesn't have a dog

The oldest person to own a dog is Debra, 30 years old and the dog is Rex (not vaccinated)


Store your program in a file called hw10b.py and submit it here.



Note: Solutions of the type shown below will be given negative points...

print( "Debra, 30 years old has a non vaccinated dog called Rex" )
print( "Millie, 25 years old has a non vaccinated dog called Maxi" )
print()
print( "Frank, 31 years old doesn't have a dog" )
print()
print( "The oldest person to own a dog is Debra, 30 "
          +"years old and the dog is Rex (not vaccinated)")
print()