Difference between revisions of "CSC111 Lab 11 2018"

From dftwiki3
Jump to: navigation, search
 
(5 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:44, 15 April 2018 (EDT)
 
[[User:Thiebaut|D. Thiebaut]] ([[User talk:Thiebaut|talk]]) 10:44, 15 April 2018 (EDT)
 
----
 
----
 +
<onlydft>
 
=Problem 1: Class Inheritance in a Graphic Context=
 
=Problem 1: Class Inheritance in a Graphic Context=
 
<br />
 
<br />
Line 388: Line 389:
 
42, Bill Clinton, 20/01/1993, 20/01/2001, Democratic, Arkansas
 
42, Bill Clinton, 20/01/1993, 20/01/2001, Democratic, Arkansas
 
43, George W. Bush, 20/01/2001, 20/01/2009, Republican, Texas
 
43, George W. Bush, 20/01/2001, 20/01/2009, Republican, Texas
 +
44, Barack Obama, 20/01/2009, 20/01/2017, Democratic, Illinois
 +
45, Donald Trump, 20/10/2017, present, Republican, New York
  
 
</source>
 
</source>
Line 393: Line 396:
 
==Example output==
 
==Example output==
 
<br />
 
<br />
 +
When generating your output, print a header for each list printed, and include the word "president" in this line (upper or lower case).  This will help the autograder figure out where your lists start and stop.
 
::<source lang="text">
 
::<source lang="text">
  
Line 431: Line 435:
 
</source>
 
</source>
 
<br />
 
<br />
 +
 
=Moodle Submission=
 
=Moodle Submission=
 
<br />
 
<br />
Line 440: Line 445:
 
<br />
 
<br />
 
<br />
 
<br />
 +
</onlydft>
 
<!-- ========================================================================================
 
<!-- ========================================================================================
 
                                         SOLUTION PROGRAMS
 
                                         SOLUTION PROGRAMS
 
     ======================================================================================== -->
 
     ======================================================================================== -->
<showafterdate after="201800420 12:00" before="20180601 00:00">
+
<showafterdate after="20180423 12:00" before="20180601 00:00">
  
 
=Solution Programs=
 
=Solution Programs=

Latest revision as of 13:01, 1 June 2018

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



...

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

Solution Programs


genericCar.py


from graphics import *
from random import *

class GenericCar:
    """Definition for a car with a body and two wheels"""

    def __init__(self, win, topLeft, width, height ):
        """constructs a car made of 1 rectangle with top-left
        point topLeft, dimension width x height, and two wheels
        away from left and right by 10 pixesl"""
        # save width and height of car
        self.width = width
        self.height = height
        
        # create bottom-right point
        x1 = topLeft.getX()
        y1 = topLeft.getY()
        P2 = Point( x1+width, y1+height )

        # body is a rectangle between topLeft and P2
        self.body = Rectangle( topLeft, P2 )
        self.body.setFill( "yellow" )

        # create wheel #1
        center1 = Point( x1+20, y1+height )
        self.wheel1 = Circle( center1, 20 )
        self.wheel1.setFill( "black" )

        # create wheel #2
        center2 = Point( x1+width-20, y1+height )
        self.wheel2 = Circle( center2, 20 )
        self.wheel2.setFill( "black" )

        # create random speed
        self.dx = randrange( -3, 3 )

        # save window width (so that a car can detect
        # that it's going outside the left or right
        # margins)
        self.windowWidth = win.getWidth()

    def setSpeed( self, speed ):
        self.dx = speed
        
    def setFill( self, color ):
        '''sets the color of the body of the car'''
        self.body.setFill( color )
        
    def draw( self, win ):
        """draw the car on the window"""
        self.body.draw( win )
        self.wheel1.draw( win )
        self.wheel2.draw( win )
            
    def move( self ):
        """move the body and wheels of the car by dx"""
        self.body.move( self.dx, 0 )
        self.wheel1.move( self.dx, 0 )
        self.wheel2.move( self.dx, 0 )

class Taxi( GenericCar ):
   '''A class derived from the GenericCar class, with
   a yellow body, and the word "TAXI" on the side of its
   body.'''
   def __init__( self, win, topLeft, width, height ):
      super().__init__( win, topLeft, width, height )
      x = (self.body.getP1().getX() + self.body.getP2().getX() )//2
      y = (self.body.getP1().getY() + self.body.getP2().getY() )//2
      self.label = Text( Point( x, y ), "T A X I" )

   def draw( self, win ):
     super().draw( win )
     self.label.draw( win )

   def move( self ):
      super().move()
      self.label.move( self.dx, 0 )
      

   def setFill( self, color ):
     return

   
class CarWithTop( GenericCar ):
   def __init__(self, win, topLeft, width, height ):
     super().__init__( win, topLeft, width, height )
     x1 = topLeft.getX()+20
     y1 = topLeft.getY()
     x2 = topLeft.getX()+self.width-20
     y2 = topLeft.getY()-30
     self.top = Rectangle( Point( x1, y1 ), Point( x2, y2 ) )
     
   def draw( self, win ):
     super().draw( win )
     self.top.draw( win )

   def setFill( self, color ):
     super().setFill( color )
     self.top.setFill( color )

   def move( self ):
     super().move()
     self.top.move( self.dx, 0 )

manyCars.py


# ManyCars.py
# A program that uses many different classes
# of cars, inherited from the GenericCar super
# class.
from genericCar import *
from graphics import *
WIDTH  = 700
HEIGHT = 500
def main():
    # open a graphic window
    win = GraphWin( "Cars Cars Cars", WIDTH, HEIGHT )

    # create a generic car, draw it, set its speed
    # and set its color to blue
    car = GenericCar( win, Point( 100, 100 ), 200, 50 )
    car.draw( win )
    car.setSpeed( -1.5 )
    car.setFill( "blue" )

    taxi = Taxi(  win, Point( 150, 200 ), 200, 50 )
    taxi.draw( win )
    taxi.setSpeed( 1.5 )
    taxi.setFill( "lightblue" )
    # keep on moving the car until the user clicks the mouse
    
    while win.checkMouse()==None:
        car.move( )
        taxi.move( )
        
    # close the graphic window        
    win.close()

main()

Solution Programs

Animals


# animals.py
# D. Thiebaut
# parses a list of lines containing
# animal information and outputs several
# interesting statistics about the quantities
# contained in the text.

text = """Black Mamba Snake 20.0 mph 
Cape Hunting Dog 45.0 mph 
Cat (domestic) 30.0 mph 
Cheetah 70.0 mph 
Chicken 9.0 mph 
Coyote 43.0 mph 
Elephant 25.0 mph 
Elk 45.0 mph 
Giant Tortoise 0.2 mph 
Giraffe 32.0 mph 
Gray Fox 42.0 mph 
Greyhound 39.4 mph 
Grizzly Bear 30.0 mph 
Human 27.9 mph 
Hyena 40.0 mph 
Jackal 35.0 mph 
Lion 50.0 mph 
Mongolian Wild Ass 40.0 mph 
Mule Deer 35.0 mph 
Pig (domestic) 11.0 mph 
Pronghorn Antelope 61.0 mph 
Quarter Horse 47.5 mph 
Rabbit (domestic) 35.0 mph 
Reindeer 32.0 mph 
Six-Lined Racerunner 18.0 mph 
Spider (Tegenaria atrica) 1.2 mph 
Squirrel 12.0 mph 
Thomson's Gazelle 50.0 mph 
Three-Toed Sloth 0.1 mph
Warthog 30.0 mph 
Whippet 35.5 mph 
White-Tailed Deer 30.0 mph 
Wild Turkey 15.0 mph 
Wildebeest 50.0 mph 
Zebra 40.0 mph"""

def main():
    #----------------------------------------------------------
    # display the list sorted by decreasing speed
    #----------------------------------------------------------
    print( "\n\nCOMPLETE LIST, ORDERED BY DECREASING SPEED" )
    list = []
    for line in text.split( "\n" ):
        fields = line.split( )
        # skip lines that do not contain a valid count of fields
        if len( fields ) < 3:
            continue

        # create a name and a speed
        name = fields[0:-2]         # all fields except last 2
        name = " ".join( name )     # join all fields with a space
        speed = float( fields[-2] ) # one before last field

        # create a tuple with speed listed first
        tuple = (speed, name )

        # add it to the list
        list.append( tuple )

    # sort the list in increasing order (smallest speed first)
    list.sort()

    # reverse the list
    list.reverse()

    # display the list
    for speed, name in list:
        print( "{0:30} {1:3.1f}".format( name, speed ) )


    #----------------------------------------------------------
    # display the 10 fastest in order of decreasing speed
    #----------------------------------------------------------
    print( "\n\n10 FASTEST ANIMALS, ORDERED BY DECREASING SPEED" )
    for i in range( min( 10, len( list ) ) ):
        speed, name = list[i]
        print( "{0:30} {1:3.1f}".format( name, speed ) )

    #----------------------------------------------------------
    # display the 10 slowest in order of decreasing speed
    #----------------------------------------------------------
    print( "\n\n10 SLOWEST ANIMALS, ORDERED BY INCREASING SPEED" )
    list.reverse()
    for i in range( min( 10, len( list ) ) ):
        speed, name = list[i]
        print( "{0:30} {1:3.1f}".format( name, speed ) )

    #----------------------------------------------------------
    # display the ratio of fastest to slowest
    #----------------------------------------------------------
    print( "\n\nSPEED-RATIO OF FASTEST TO SLOWEST" )
    fastestSpeed, fastestName = list[-1]
    slowestSpeed, slowestName = list[0]
    print( "The {0:1} is {1:1.0f} times faster than the {2:1}."
           .format( fastestName, fastestSpeed/slowestSpeed, slowestName ))

    #----------------------------------------------------------
    # display the animals faster than human beings
    #----------------------------------------------------------
    print( "\n\nANIMALS FASTER THAN HUMAN BEINGS" )

    # find the speed of the human
    speedHuman = 0
    for speed, name in list:
        if name.strip().lower()=="human":
            speedHuman = speed
            break

    # create a list of the animals faster than humans
    list2 = []
    for speed, name in list:
        if speed > speedHuman:
            list2.append( name )

    # sort the list alphabetically
    list2.sort()

    # display the list
    for name in list2:
        print( "{0:30}".format( name, speed ) )


if __name__=="__main__":
    main()


Aquarium


# aquariumLab11.py
# D. Thiebaut
# A graphics program based on Zelle's graphic library.
# Creates an application with the picture of an aquarium
# as the backdrop, then creates a school of fish, and animates
# them, having them move around the aquarium, in a somewhat
# random fashion.
from graphics import *
import random

WIDTH  = 700
HEIGHT = 517

class Fish:
    """A class for the fish.  Supports randomly moving in the
    right to left direction"""

    def __init__(self, fileName ):
        self.img = Image( Point( random.randrange( WIDTH//2, WIDTH),
                         random.randrange( HEIGHT) ), fileName )

    def draw( self, win ):
        """shows the fish on the graphics window"""
        self.img.draw( win )

    def moveRandom( self ):
        """moves the fish to the right, randomly.  Some random up/down motion"""
        deltaX = random.randrange( -5, 0 )
        deltaY = random.randrange( -3, 4 )
        self.img.move( deltaX, deltaY )
        if self.img.getAnchor().getX() < -50:
           self.img.move( WIDTH + 100, 0 )
        
def main():
    # open the window
    win = GraphWin( "CSC Aquarium", WIDTH, HEIGHT )

    # display background
    background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" )
    background.draw( win )

    # create a school of fish
    fishList = []
    for i in range( 10 ):
        fish = Fish( "fish0.gif" )
        fish.draw( win )
        fishList.append( fish )

    # animation loop.
    while win.checkMouse() == None:
        for fish in fishList:
            fish.moveRandom()
   

    # one more click to close the window.
    win.getMouse()
    win.close()
    
main()


Presidents


# presidents.py
# D. Thiebaut
# A program that processes a list of presidents and extracts list of 
# presidents with particular attributes.
text="""Presidency ,President, Took office ,Left office ,Party , Home State
1, George Washington, 30/04/1789, 4/03/1797, Independent, Virginia
2, John Adams, 4/03/1797, 4/03/1801, Federalist, Massachusetts
3, Thomas Jefferson, 4/03/1801, 4/03/1809, Democratic-Republican, Virginia
4, James Madison, 4/03/1809, 4/03/1817, Democratic-Republican, Virginia
5, James Monroe, 4/03/1817, 4/03/1825, Democratic-Republican, Virginia
6, John Quincy Adams, 4/03/1825, 4/03/1829, Democratic-Republican/National Republican, Massachusetts
7, Andrew Jackson, 4/03/1829, 4/03/1837, Democratic, Tennessee
8, Martin Van Buren, 4/03/1837, 4/03/1841, Democratic, New York
9, William Henry Harrison, 4/03/1841, 4/04/1841, Whig, Ohio
10, John Tyler, 4/04/1841, 4/03/1845, Whig, Virginia
11, James K. Polk, 4/03/1845, 4/03/1849, Democratic, Tennessee
12, Zachary Taylor, 4/03/1849, 9/07/1850, Whig, Louisiana
13, Millard Fillmore, 9/07/1850, 4/03/1853, Whig, New York
14, Franklin Pierce, 4/03/1853, 4/03/1857, Democratic, New Hampshire
15, James Buchanan, 4/03/1857, 4/03/1861, Democratic, Pennsylvania
16, Abraham Lincoln, 4/03/1861, 15/04/1865, Republican/National Union, Illinois
17, Andrew Johnson, 15/04/1865, 4/03/1869, Democratic/National Union, Tennessee
18, Ulysses S. Grant, 4/03/1869, 4/03/1877, Republican, Ohio
19, Rutherford B. Hayes, 4/03/1877, 4/03/1881, Republican, Ohio
20, James A. Garfield, 4/03/1881, 19/09/1881, Republican, Ohio
21, Chester A. Arthur, 19/09/1881, 4/03/1885, Republican, New York
22, Grover Cleveland, 4/03/1885, 4/03/1889, Democratic, New York
23, Benjamin Harrison, 4/03/1889, 4/03/1893, Republican, Indiana
24, Grover Cleveland, 4/03/1893, 4/03/1897, Democratic, New York
25, William McKinley, 4/03/1897, 14/9/1901, Republican, Ohio
26, Theodore Roosevelt, 14/9/1901, 4/3/1909, Republican, New York
27, William Howard Taft, 4/3/1909, 4/03/1913, Republican, Ohio
28, Woodrow Wilson, 4/03/1913, 4/03/1921, Democratic, New Jersey
29, Warren G. Harding, 4/03/1921, 2/8/1923, Republican, Ohio
30, Calvin Coolidge, 2/8/1923, 4/03/1929, Republican, Massachusetts
31, Herbert Hoover, 4/03/1929, 4/03/1933, Republican, Iowa
32, Franklin D. Roosevelt, 4/03/1933, 12/4/1945, Democratic, New York
33, Harry S. Truman, 12/4/1945, 20/01/1953, Democratic, Missouri
34, Dwight D. Eisenhower, 20/01/1953, 20/01/1961, Republican, Texas
35, John F. Kennedy, 20/01/1961, 22/11/1963, Democratic, Massachusetts
36, Lyndon B. Johnson, 22/11/1963, 20/1/1969, Democratic, Texas
37, Richard Nixon, 20/1/1969, 9/8/1974, Republican, California
38, Gerald Ford, 9/8/1974, 20/01/1977, Republican, Michigan
39, Jimmy Carter, 20/01/1977, 20/01/1981, Democratic, Georgia
40, Ronald Reagan, 20/01/1981, 20/01/1989, Republican, California
41, George H. W. Bush, 20/01/1989, 20/01/1993, Republican, Texas
42, Bill Clinton, 20/01/1993, 20/01/2001, Democratic, Arkansas
43, George W. Bush, 20/01/2001, 20/01/2009, Republican, Texas"""

def main():
    # remove the first line from the list of lines
    lines = text.split( "\n" )
    lines = lines[1:]

    # create a list of tuples
    list = []
    for line in lines:
        fields = line.split( "," )

        # skip invalid lines
        if len( fields ) != 6:
            continue

        # create tuple
        name = fields[1].strip()
        yearStart = int( fields[2].split( "/" )[2] )
        yearEnd   = int( fields[3].split( "/" )[2] )
        party     = fields[-2].strip()
        state     = fields[-1].strip()
        tuple = ( name, yearStart, yearEnd, party, state )

        # add tuple to list
        list.append( tuple )

    #=========================================================
    # Display the list of presidents in alphabetical order
    #=========================================================
    print( "\n\nAlphabetical List of presidents".upper() )
    list.sort()
    for name, y1, y2, party, s in list:
        print( name )
        

    #=========================================================
    # Display the list of presidents associated with the democratic
    # party
    #=========================================================
    print( "\n\nAlphabetical List of Democrats".upper() )
    for name, y1, y2, party, s in list:
        if party.lower().find( "democra" )!= -1:
            print( name )
        
    #=========================================================
    # Display the president in office in 1945
    #=========================================================
    print( "\n\nPresidents in office in 1945".upper() )
    for name, y1, y2, party, s in list:
        if y1 <= 1945 <= y2:
            print( name )


    #=========================================================
    # Display the president whose home state was Massachusetts
    #=========================================================
    print( "\n\nPresidents from Massachusetts".upper() )
    for name, y1, y2, party, s in list:
        if s.capitalize().find( "Massa" ) != -1:
            print( name )
    
if __name__=="__main__":
    main()


</showafterdate>