CSC111 Lab 10 Solution Programs 2014

From dftwiki3
Revision as of 16:48, 10 April 2014 by Thiebaut (talk | contribs)
Jump to: navigation, search

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


# Lab 10 solution programs
# D. Thiebaut
#

 
text = """
Alex, 20, 3.6, ART
Lulu, 21, 3.5, BIO
Alka, 19, 3.0, ENG
Le, 21, 3.2, EGR
"""

SWsFriends = [
    # name    pocket-money  debt
    ("Sleepy",  10,         "NA" ),
    ("Sneezy",  25.50,      0 ),
    ("Bashful", 0.50,       10.51 ),
    ( "Happy",  0,          0 ),
    ( "Grumpy", 0,          100.30 ),
    ( "Dopey",  "NA",       0 ),
    ( "Doc",    200,        0 ) ]

def main0():
    # display everybody's status
    for name, pocket, debt in SWsFriends:
        print( name, "has", pocket, "dollar(s) in his pocket, and owes",
                debt, "dollar(s)" )

    # compute sum in pockets 
    print( "\n\n" )
    sumPocket = 0
    for name, pocket, debt in SWsFriends:
        try:
            sumPocket += pocket
        except TypeError as err:
            print( "*** Error ***:", err.args[0] )

    print( "Total in pocket = ", sumPocket )

    # compute total debt
    print( "\n\n" )
    totalDebt = 0
    for name, pocket, debt in SWsFriends:
        try:
            totalDebt += debt
        except TypeError as err:
            print( "*** Error ***:", err.args[0] )

    print( "Total debt = ", totalDebt )

    # nicely formatted output
    print( "\n\n" )
    for name, pocket, debt in SWsFriends:
        try:
            pocketStr = "%7.2f" % float( pocket )
        except ValueError as err:
            #print( "*** Error ***:", err.args[0] )
            pocketStr = "%7s" % "NA"

        try:
            debtStr = "%7.2f" % float( debt )
        except ValueError as err:
            #print( "*** Error ***:", err.args[0] )
            debtStr = "%7s" % "NA"

        print( "%10s %s %s" % ( name, pocketStr, debtStr ) )

    
 
# ================================================================
# ____                           
#|  _ \ ___ _ __ ___  ___  _ __  
#| |_) / _ \ '__/ __|/ _ \| '_ \ 
#|  __/  __/ |  \__ \ (_) | | | |
#|_|   \___|_|  |___/\___/|_| |_|
#
class Person:
    # a class containing 4 fields:
    # - name of the person (string)
    # - age (integer)
    # - gpa (float)
    # - major (string, uppercase)

    # constructor: intializes a person with all fields
    def __init__(self, n, a, g, m):
        self._name = n
        self._age  = a
        self._gpa  = g
        self._major= m

    # returns a string with the name and age.
    def toString( self ):
        return "\t%s\t\t%d" % ( 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:
    def __init__(self, tn, a, v, b ):
        self._tagName    = tn
        self._age        = a
        self._vaccinated = v
        self._breed      = b

    def toString( self ):
        vacc = "vaccinated"
        if not self._vaccinated:
            vacc = "not " + vacc
        return "%s, %d years old, %s, %s" % (
                  self._tagName,
                  self._age,
                  vacc,
                  self._breed )

    def isVaccinated( self ):
        return self._vaccinated

    def getBreed( self ):
        return self._breed

# ================================================================
# ____  _                  _   _     _     _   
#|  _ \| | __ _ _ __   ___| |_| |   (_)___| |_ 
#| |_) | |/ _` | '_ \ / _ \ __| |   | / __| __|
#|  __/| | (_| | | | |  __/ |_| |___| \__ \ |_ 
#|_|   |_|\__,_|_| |_|\___|\__|_____|_|___/\__|
#
class PlanetList:
    def __init__( self ):
        self._list = [("Earth", 12756 ),
                      ("Venus", 12104 ),
                      ("Mercury", 4880 ),
                      ("Moon", 3476 ) ]
        
    def toString( self ):
        justNames = [ name for name,diameter in self._list ]
        return ", ".join( justNames )

    def addNewPlanetFromInput( self ):
        name = input( "What is the name of the new planet? " )
        name = name.strip().capitalize()
        justNames = [ name for name,diameter in self._list ]
        if name in justNames:
            print( "This planet is alread in the list!" )
            return
        diameter = int( input( "What is the diameter of this planet? " ) )
        self._list.append( (name, diameter) )

    def noOfPlanets( self ):
        return len( self._list )

    def isEmpty( self ):
        return len( self._list )==0
    
    def smallest( self ):
        if self.noOfPlanets() == 0:
            return None
        listOrderedBySize = [ (diam, name) for name, diam in self._list ]
        listOrderedBySize.sort()
        
        # return the name (2nd argument) of the first in list
        return listOrderedBySize[0][1]

    def largest( self ):
        if self.noOfPlanets() == 0:
            return None
        listOrderedBySize = [ (diam, name) for name, diam in self._list ]
        listOrderedBySize.sort()
        listOrderedBySize.reverse()
        
        # return the name (2nd argument) of the first in list
        return listOrderedBySize[0][1]

# =================================================================    
def playWithPeople():
    # create a list of people taken from the text
    people = []
    for line in text.split( "\n" ):
        words = line.split( "," )
        
        # skip ill-formed lines
        if len( words ) != 4:
            continue
        
        # strip each word
        words = [ w.strip() for w in words ]

        person = Person( words[0], int( words[1] ), float( words[2] ), words[3] )
        people.append( person )

    # display the list of names and their age
    print( "Names: " )
    for person in people:
        print( person.toString() )

    # add a new person to the list
    people.append( Person("Xiaole", 21, 3.9, "CSC") )

    # modify age of person named Alka
    for person in people:
        if person.getName().lower() == "alka":
            person.setAge( person.getAge() + 1 )

    # display the list of names and their age
    print( "Names: " )
    for person in people:
        print( person.toString() )

# =================================================================    
def displayDogs( list, caption ):
    print( caption )
    for dog in list:
        print( dog.toString() )
    print()
    
def playWithDogs():
    dogs = []
    dogs.append( Dog( "Rex", 4, True, "German Shepherd" ) )

    displayDogs( dogs, "List of 1 dog" )

    dogs.append( Dog( "Fifi", 1, False, "Poodle" ) )
    dogs.append( Dog( "Samson", 3, True, "Great Dane" ) )
    dogs.append( Dog( "Mad Max", 2, False, "Poodle" ) )

    displayDogs( dogs, "List of 4 dogs" )

    # find vaccinated dogs
    vaccinated = []
    for dog in dogs:
        if dog.isVaccinated():
            vaccinated.append( dog )
            
    displayDogs( vaccinated, "The vaccinated dogs are: " )
    
    # ask user for a breed
    breed = input( "Please enter a breed: " ).strip()

    # find all the dogs with this breed
    sameBreed = []
    for dog in dogs:
        if dog.getBreed().lower() == breed.lower():
            sameBreed.append( dog )

    displayDogs( sameBreed, "Dogs of breed "+ breed )


# =================================================================    
def playWithPlanets():

    planets = PlanetList()

    print( planets.toString() )

    largest = planets.getLargest()
    print( "Largest planet = ", largest )

    smallest = planets.getSmallest()
    print( "Smallest planet = ", smallest )

    print( "Number of planets in list: ", planets.getNoOfPlanets() )

    planets.addNewPlanetFromInput()

    print( planets.toString() )
    

# =================================================================    
def main():
    main0()
    #playWithPeople
    #playWithDogs()
    playWithPlanets()
    
main()