Difference between revisions of "CSC111 Lab 9 2018"

From dftwiki3
Jump to: navigation, search
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 09:54, 1 April 2018 (EDT)
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 09:54, 1 April 2018 (EDT)
 
----
 
----
+
<onlydft>
 
<bluebox>
 
<bluebox>
 
This lab deals with exceptions and creating classes.   
 
This lab deals with exceptions and creating classes.   
The deadline for this lab is Friday 04/6/18 at 11:55 p.m.
+
The deadline for this lab is <strike>Friday 04/6/18</strike> Sunday 4/8/18, at 11:55 p.m.
 
</bluebox>
 
</bluebox>
 
   
 
   
Line 587: Line 587:
 
;Example CSV file:
 
;Example CSV file:
 
::<source lang="text">
 
::<source lang="text">
Max, 1, vaccinated, not tattooed, stray
+
Max, 21, vaccinated, not tattooed, stray
Black, 3, not vaccinated, tattooed, stray
+
Toto, 3, not vaccinated, tattooed, stray
Gizmo, 2, vaccinated, not tattooed, Bengal
+
Garfield, 1, not vaccinated, not tattooed, Burmese
Winston, 2, vaccinated, tattooed, Bengal
 
Garfield, 3, vaccinated, not tattooed, Burmese
 
 
Bob, 4, not vaccinated, tattooed, Orange Tabby
 
Bob, 4, not vaccinated, tattooed, Orange Tabby
Minou, 1, vaccinated, tattooed, stray
+
Minou, 10, not vaccinated, not tattooed, stray
Silky, 3, not vaccinated, tattooed, Siamese
 
 
</source>
 
</source>
 
<br />
 
<br />
Line 601: Line 598:
 
::<source lang="text">
 
::<source lang="text">
 
Complete List:
 
Complete List:
Max                :==> stray, vaccinated, not tattooed, 1 yrs old
+
Max                :==> stray, vaccinated, not tattooed, 21 yrs old
Black              :==> stray, not vaccinated, tattooed, 3 yrs old
+
Toto                :==> stray, not vaccinated, tattooed, 3 yrs old
Gizmo              :==> Bengal, vaccinated, not tattooed, 2 yrs old
+
Garfield            :==> Burmese, not vaccinated, not tattooed, 1 yrs old
Winston            :==> Bengal, vaccinated, tattooed, 2 yrs old
 
Garfield            :==> Burmese, vaccinated, not tattooed, 3 yrs old
 
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
Minou              :==> stray, vaccinated, tattooed, 1 yrs old
+
Minou              :==> stray, not vaccinated, not tattooed, 10 yrs old
Silky              :==> Siamese, not vaccinated, tattooed, 3 yrs old
 
  
 
Non-vaccinated cats:
 
Non-vaccinated cats:
Black              :==> stray, not vaccinated, tattooed, 3 yrs old
+
Toto                :==> stray, not vaccinated, tattooed, 3 yrs old
 +
Garfield            :==> Burmese, not vaccinated, not tattooed, 1 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
Silky               :==> Siamese, not vaccinated, tattooed, 3 yrs old
+
Minou               :==> stray, not vaccinated, not tattooed, 10 yrs old
  
 
Stray cats:
 
Stray cats:
Max                :==> stray, vaccinated, not tattooed, 1 yrs old
+
Max                :==> stray, vaccinated, not tattooed, 21 yrs old
Black              :==> stray, not vaccinated, tattooed, 3 yrs old
+
Toto                :==> stray, not vaccinated, tattooed, 3 yrs old
Minou              :==> stray, vaccinated, tattooed, 1 yrs old
+
Minou              :==> stray, not vaccinated, not tattooed, 10 yrs old
  
 
Non-vaccinated cats 2 or older:
 
Non-vaccinated cats 2 or older:
Black              :==> stray, not vaccinated, tattooed, 3 yrs old
+
Toto                :==> stray, not vaccinated, tattooed, 3 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
Silky               :==> Siamese, not vaccinated, tattooed, 3 yrs old
+
Minou               :==> stray, not vaccinated, not tattooed, 10 yrs old
  
 
Non-tattooed cats:
 
Non-tattooed cats:
Max                :==> stray, vaccinated, not tattooed, 1 yrs old
+
Max                :==> stray, vaccinated, not tattooed, 21 yrs old
Gizmo              :==> Bengal, vaccinated, not tattooed, 2 yrs old
+
Garfield            :==> Burmese, not vaccinated, not tattooed, 1 yrs old
Garfield            :==> Burmese, vaccinated, not tattooed, 3 yrs old
+
Minou              :==> stray, not vaccinated, not tattooed, 10 yrs old
  
Vaccinated and tattooed cats:
+
Not vaccinated and tattooed cats:
Winston            :==> Bengal, vaccinated, tattooed, 2 yrs old
+
Toto                :==> stray, not vaccinated, tattooed, 3 yrs old
Minou              :==> stray, vaccinated, tattooed, 1 yrs old
 
 
 
Vaccinated and older than 2 cats:
 
Black              :==> stray, not vaccinated, tattooed, 3 yrs old
 
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
 
Bob                :==> Orange Tabby, not vaccinated, tattooed, 4 yrs old
Silky              :==> Siamese, not vaccinated, tattooed, 3 yrs old
 
  
  
Line 850: Line 840:
 
-->
 
-->
  
 
+
</onlydft>
 
<!-- ============================================================= -->
 
<!-- ============================================================= -->
 
<!-- ============================================================= -->
 
<!-- ============================================================= -->
Line 856: Line 846:
 
<!-- ============================================================= -->
 
<!-- ============================================================= -->
  
<showafterdate after="20180407 12:00" before="20180601 00:00">
+
<showafterdate after="20180409 12:00" before="20180601 00:00">
 
=Solution Programs=
 
=Solution Programs=
 
==Part 1 ==
 
==Part 1 ==

Latest revision as of 12:59, 1 June 2018

D. Thiebaut (talk) 09:54, 1 April 2018 (EDT)



...


<showafterdate after="20180409 12:00" before="20180601 00:00">

Solution Programs

Part 1


# lab9 programs
# D. Thiebaut

# getInput: returns an integer larger
# than 0.  Expected to be robust
def getInput():
   
   while  True:
      x = int( input( "Enter an integer greater than 0: " ) )
      if x <= 0:
         print( "Invalid entry.  Try again!" )
      else:   
         return x

# betterGetInput: returns an integer larger
# than 0.  Expected to be robust
def betterGetInput():
    
   # repeat forever...
   while  True:

      # try to get an int
      try:
          x = int( input( "Enter an integer greater than 0: " ) )
      except ValueError:
          # the user must have entered something other than an int
          print( "Invalid entry.  Not an integer.  Try again!" )
          continue

      # There was no errors.  See if the number is negative
      if x <= 0:
         print( "You entered a negative number.  Try again!" )
      else:   
         return x

def main1():
   num = betterGetInput()
   print( "You have entered", num )

# =======================================================================

def example1():
    print( "You will need to enter 3 pairs of ints..." )
    while True:
       try:
            x = int( input( "enter a number: " ) )
            y = int( input( "enter another number: " ) )
            print( x, '/', y, '=', x/y )
            break
       except ZeroDivisionError:
            print( "Can't divide by 0!" )
       except ValueError:
            print( "That doesn't look like a number!" )
       except:
            print( "something unexpected happend!" )

def example2( L ):
    print( "\n\nExample 2" )
    sum = 0
    for i in range( len( L ) ):
        try:
            sum +=  L[i]
        except TypeError:
            continue

    print( "sum of items in ", L, "=", sum )


def printUpperFile( fileName ):
    try:
       file = open( fileName, "r" )
    except FileNotFoundError:
       print( "***Error*** File", fileName, "not found!" )
       return

    # if we're here, the file is found and open
    for line in file:
       print( line.upper() )
    file.close()

def createTextFile( fileName ):
   file = open( fileName, "w" )
   file.write( "Welcome\nto\nCSC111\nIntroduction\nto\nComp.\nSci.\n" )
   file.close()

def main2():
    createTextFile( "csc111.txt" )

    example1()

    L = [ 10, 3, 5, 6, 9, 3 ]
    example2( L )
    #example2( [ 10, 3, 5, 6, "NA", 3 ] )

    printUpperFile( "csc111.txt" )
    #printUpperFile( "csc1111.txt" )

main2()


Part 2


# cats1.py
# D. Thiebaut
# Program for Week #9
# Define a Cat class, and
# use it to create a collection of
# cats.


class Cat:
    """a class that implements a cat and its
    information.  Name, breed, vaccinated,
    tattooed, and age."""

    def __init__( self, na, brd, vacc, ag, tat ):
        """constructor.  Builds a cat with all its information"""
        self.name       = na
        self.breed      = brd
        self.vaccinated = vacc
        self.age        = ag
        self.tattooed   = tat

    def isTattooed( self ):
        """returns True if cat is tattooed, False otherwise"""
        return self.tattooed

    def isVaccinated( self ):
        """returns True if cat is vaccinated, False otherwise"""
        return self.vaccinated

    def getAge( self ):
        """returns cat's age"""
        return self.age

    def getName( self ):
        """returns name of cat"""
        return self.name

    def getBreed( self ):
        return self.breed
    
    def __str__( self ):
        """default string representation of cat"""
        vacc = "vaccinated"
        if not self.vaccinated:
            vacc = "not vaccinated"

        tatt = "tattooed"
        if not self.tattooed:
            tatt = "not tattooed"
        
        return "{0:20}:==> {1:1}, {2:1}, {3:1}, {4:1} yrs old".format(
            self.name, self.breed, vacc, tatt, self.age )

def readCatCSV( fileName ):
    """ reads the CSV file and puts all the cats
    in a list of Cat objects"""

    # get the lines from the CSV file
    file = open( fileName, "r" )
    lines = file.readlines()
    file.close()

    # create an empty list of cats
    cats = []
    
    # get one line at a time
    for line in lines:
        # split a line in words
        fields = line.split( ", " )

        # skip lines that do not have 5 fields
        if len( fields ) != 5:
            continue

        # get 5 fields into 5 different variables
        name, age, vac, tat, breed = fields
        breed = breed.strip()
        
        # transform "vaccinated" or "not vaccinated" in True or False
        if vac.lower().find( "not " )==-1:
            vac = True
        else:
            vac = False
            
        # transform "tattooed" or "not tattooed" in True or False
        if tat.lower().find( "not " )==-1:
            tat = True
        else:
            tat = False

        # add a new cat to the list
        cats.append( Cat( name, breed, vac, int(age), tat ) )

    # done with the lines.  Return the cat list
    return cats

def main():
    """ main program.  Creates a list of cats and displays
    groups sharing the same property.
        Minou, 3, vac, stray, tat
        Max, 1, not-vac, Burmese, tat
        Gizmo, 2, vac, Bengal, tat
        Garfield, 4, not-vac, Orange Tabby
    """
    cats = readCatCSV( input( "File name? " ) )
    """
    cat = Cat( "Minou", "stray", True, 3, True)
    cats.append( cat )
    
    cats.append( Cat( "Max", "Burmese", False, 1, True ) )
    cats.append( Cat( "Gizmo", "Bengal", True, 2, True ) )
    cats.append( Cat( "Garfield", "Orange Tabby", False, 4, False ) )
    """
    
    # print the list of all the cats
    print( "\nComplete List:" )
    for cat in cats:
        print( cat )

    print( "\nNon-vaccinated cats:" )
    for cat in cats:
        if cat.isVaccinated()==False:
            print( cat )

    print( "\nStray cats:" )
    for cat in cats:
        if cat.getBreed().lower() == "stray":
            print( cat )

    print( "\nNon-vaccinated cats 2 or older:" )
    for cat in cats:
        if cat.isVaccinated()==False and cat.getAge() >= 2:
            print( cat )

    print( "\nNon-tattooed cats:" )
    for cat in cats:
        if cat.isTattooed()==False:
            print( cat )
            
    print( "\nVaccinated and tattooed cats:" )
    for cat in cats:
        if cat.isVaccinated() and cat.isTattooed():
            print( cat )

def lab9Solution():
    """prompts user for file name, and outputs
    cats that are not vaccinated, and 2 years or older"""
    
    cats = readCatCSV( input( "File name? " ) )
    print()

    for cat in cats:
        if cat.isVaccinated()==False and cat.getAge() >= 2:
            print( cat )
            
#main()
lab9Solution()


</showafterdate>