Difference between revisions of "CSC111 Lab 11 2018"
(→Main Module) |
|||
(16 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 140: | Line 141: | ||
</source> | </source> | ||
===Draw method=== | ===Draw method=== | ||
− | |||
* Add a '''draw()''' method to your taxi. It will call the draw() method of the super class (see how __init__() calls the __init__() constructor of the super class, and do the same for draw(). Your draw() method needs to call draw() of the super class to draw the body and wheels, and it needs to draw the self.label. | * Add a '''draw()''' method to your taxi. It will call the draw() method of the super class (see how __init__() calls the __init__() constructor of the super class, and do the same for draw(). Your draw() method needs to call draw() of the super class to draw the body and wheels, and it needs to draw the self.label. | ||
* Save genericCar.py after your edit is done. | * Save genericCar.py after your edit is done. | ||
− | * Modify '''manyCars.py''' and add a taxi object, instantiated from your new Taxi class. Mirror what you did with your first two cars, creating the taxi, drawing the taxi, and moving the taxi. | + | * Modify '''manyCars.py''' and add a taxi object, instantiated from your new Taxi class. Mirror what you did with your first two cars, creating the taxi, setting its color to, say, "lightblue", drawing the taxi, and moving the taxi. |
* Run '''manyCars.py''', and observe that some things are not quite working well... | * Run '''manyCars.py''', and observe that some things are not quite working well... | ||
+ | ===Move method=== | ||
+ | * You will have noticed that the default '''move''' method from the GenericClass needs to be overloaded, because it does more the car and the wheels, but not the "TAXI" label. Create a new move() method for your Taxi: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | def move( self ): | ||
+ | super().move() | ||
+ | self.label.move( self.dx, 0 ) | ||
+ | |||
+ | </source> | ||
+ | * Run '''manyCars.py''' again, and verify that your label now moves with the car. | ||
+ | |||
+ | ===setFill method=== | ||
+ | * Make sure your manyCars.py program sets the color of your taxi to some color other than yellow. You will have noticed that your taxi gets painted that color, and not the default yellow we'd like for all our taxis. So you need to overload the '''setFill()''' method of '''Taxi''' so that it sets the color to "yellow," no matter what color the main program tries to set. | ||
+ | * You may also set the color of the taxi in the constructor, to be safe. | ||
+ | * Run '''manyCars.py''' again, and verify that your taxi now is yellow and that its label move with the body. | ||
+ | |||
+ | <br /> | ||
+ | ==Creating a second derived class: CarWithTop== | ||
+ | <br /> | ||
+ | Using the same approach you did when you created your '''Taxi''' class, create a new class ''derived'' from '''GenericCar''', and call it '''CarWithTop'''. This class will be used to create cars that have GenericCar as a super class, but that sport a top (see the pink car in the image at the top of this page). | ||
+ | <br /> | ||
+ | * Go ahead and create the class '''CarWithTop''', with | ||
+ | ::* a constructor | ||
+ | ::* whatever other methods are required for the car to move nicely across the graphic window. | ||
+ | * Add a new object of type CarWithTop to your '''manyCars.py''' module. | ||
+ | * Verify that all cars are moving smoothly across the graphic window. | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <!-- ================================================================ --> | ||
+ | |||
+ | =Problem 2: Aquarium= | ||
+ | <br /> | ||
+ | * Point your browser to [[Fish_for_an_Aquarium|this page]] and drag the tank image and a couple fish images to your desktop. | ||
+ | |||
+ | * Write a new program called '''lab11_2.py''' and copy/paste the following code in it: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # lab11_2.py | ||
+ | # Displays fish in an aquarium | ||
+ | |||
+ | from graphics import * | ||
+ | import random | ||
+ | |||
+ | WIDTH = 700 # geometry of the tank2.gif file | ||
+ | HEIGHT = 517 | ||
+ | |||
+ | |||
+ | def main(): | ||
+ | # open the window | ||
+ | win = GraphWin( "CSC Aquarium", WIDTH, HEIGHT ) | ||
+ | |||
+ | # display background image | ||
+ | background = Image( Point( WIDTH//2, HEIGHT//2 ), "tank2.gif" ) | ||
+ | background.draw( win ) | ||
+ | |||
+ | # display the image of a fish at a random location | ||
+ | fish = Image( Point( random.randrange( WIDTH), | ||
+ | random.randrange( HEIGHT) ), | ||
+ | "fish0.gif" ) | ||
+ | fish.draw( win ) | ||
+ | |||
+ | # close window when user clicks it | ||
+ | win.getMouse() | ||
+ | win.close() | ||
+ | |||
+ | main() | ||
+ | |||
+ | |||
+ | |||
+ | </source> | ||
+ | |||
+ | * Create a new class called '''Fish'''. | ||
+ | * Include a '''constructor''' that received the name of the gif file for the fish. | ||
+ | * Include a '''member variable''' in the class to hold the image (Image class in graphics.py) of the fish. | ||
+ | * Add a '''draw()''' method to the class, that will allow the main program to have the fish draw itself on the graphic window (win). | ||
+ | * Add a '''moveRandom()''' method to the class, that will move the image of the fish some random deltaX and deltaY on the graphic window. Reminder: user <tt>random.randrange( 10 )</tt> to generate a random number between 0 and 10, and use <tt>random.randrange( -10, 0 )</tt> to generate a random number between -10 and 0 (not included). | ||
+ | * Modify the main program so that it simply creates and displays a fish object, as shown below: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | 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 ) | ||
+ | |||
+ | # display a fish | ||
+ | fish = Fish( "fish0.gif" ) | ||
+ | fish.draw( win ) | ||
+ | |||
+ | win.getMouse() | ||
+ | win.close() | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | * When your code works, and only then, add a loop to make the fish move: | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | 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 ) | ||
+ | |||
+ | # display a fish | ||
+ | fish = Fish( "fish0.gif" ) | ||
+ | fish.draw( win ) | ||
+ | |||
+ | # animation loop | ||
+ | while win.checkMouse() == None: | ||
+ | fish.moveRandom() | ||
+ | |||
+ | win.getMouse() | ||
+ | win.close() | ||
+ | |||
+ | </source> | ||
+ | |||
+ | <br /> | ||
+ | * Modify the moveRandom() method so that the fish disappears from the graphics window, it is moved back on the other side of the aquarium. | ||
+ | * Create a list of 10 fish with the "fish0.gif" image, and add 10 fish with the "fish20.gif" image (or some fish that is headed in the opposite direction). | ||
+ | * Modify the Fish class so that you can define the direction a fish goes into when you create it. | ||
+ | * Verify that the fish swim in the correct direction. | ||
+ | * Demonstrate your program to the lab instructor or a TA when you're done. | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <!-- ================================================================ --> | ||
+ | <!-- LIST OF LISTS --> | ||
+ | <!-- ================================================================ --> | ||
+ | =List of Lists= | ||
+ | ==Demonstration Example== | ||
+ | <br /> | ||
+ | * Create a new new program called '''Lab11_demo.py''' and copy the code from this [[CSC111 List of Tuples Demo| program]][http://cs.smith.edu/dftwiki/index.php/CSC111_List_of_Tuples_Demo .] | ||
+ | * Carefully read the program to see what it does, and how it does it. | ||
+ | * Run the program to verify that it works well. | ||
+ | * Edit the text variable, and make it contain only 5 lines of text (it doesn't matter what countries you pick). | ||
+ | * Run your program again and verify that the "top-10" and "last-10" sections still work and do not crash, even though the list contains fewer than 10 tuples. | ||
+ | * Using a similar approach, solve the next two problems. | ||
+ | <br /> | ||
+ | |||
+ | <!-- ================================================================ --> | ||
+ | =Problem 3: Animals= | ||
+ | <br /> | ||
+ | The text below contains names of animals and their speed, expressed in miles per hour. Write a Python program called '''Lab11_3.py''' (no need to write classes for this problem) based on the preparation problem above, and make your program output the following quantities: | ||
+ | # The list of '''all''' the animals ranked by speed. Fastest first. | ||
+ | # The 10 fastest animals listed in order of decreasing speed | ||
+ | # The 10 slowest animals listed in order of increasing speed | ||
+ | # The ratio of the speeds of the fastest animal versus that of the slowest animal. For example, if the speed of the fastest animal is 50 and the speed of the slowest is 2, then the program should output that the fastest animal is '''25 times''' faster than the slowest one. | ||
+ | # The list of all the animals (just their name, not their speed) that are faster than a human being ("human" is one of the species listed). Your program should not contain the number 27.9, which is the speed of a human. Instead it should find this number by looking up "human" in one of your lists and get the speed associated for the human. | ||
+ | <br /> | ||
+ | |||
+ | ::<source lang="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 | ||
+ | </source> | ||
+ | <br /> | ||
+ | <!-- ================================================================ --> | ||
+ | =Problem 4: Presidents= | ||
+ | <br /> | ||
+ | Below is a CSV list (coma-separated values) of past presidents. Using similar Python code as you have used for the previous problem, write a program ('''Lab11_4.py''') that will process this list and output: | ||
+ | <br /> | ||
+ | # the list of all the presidents who were associated with the democratic party. | ||
+ | # the person who was president in 1945. | ||
+ | # the presidents whose home state was Massachusetts. | ||
+ | ::<source lang="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 | ||
+ | 44, Barack Obama, 20/01/2009, 20/01/2017, Democratic, Illinois | ||
+ | 45, Donald Trump, 20/10/2017, present, Republican, New York | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | ==Example output== | ||
+ | <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"> | ||
+ | |||
+ | PRESIDENTS WHO WERE DEMOCRATS | ||
+ | Thomas Jefferson | ||
+ | James Madison | ||
+ | James Monroe | ||
+ | John Quincy Adams | ||
+ | Andrew Jackson | ||
+ | Martin Van Buren | ||
+ | James K. Polk | ||
+ | Franklin Pierce | ||
+ | James Buchanan | ||
+ | Andrew Johnson | ||
+ | Grover Cleveland | ||
+ | Grover Cleveland | ||
+ | Woodrow Wilson | ||
+ | Franklin D. Roosevelt | ||
+ | Harry S. Truman | ||
+ | John F. Kennedy | ||
+ | Lyndon B. Johnson | ||
+ | Jimmy Carter | ||
+ | Bill Clinton | ||
+ | Barack Obama | ||
+ | |||
+ | |||
+ | PRESIDENT(S) IN OFFICE IN 1945 | ||
+ | Franklin D. Roosevelt | ||
+ | Harry S. Truman | ||
+ | |||
+ | |||
+ | PRESIDENTS FROM MASSACHUSETTS | ||
+ | John Adams | ||
+ | John Quincy Adams | ||
+ | Calvin Coolidge | ||
+ | John F. Kennedy | ||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | |||
+ | =Moodle Submission= | ||
+ | <br /> | ||
+ | # Submit an image of the aquarium with your fish on Moodle, in the Lab 11 PB 2 section. | ||
+ | # Submit your solution program for the presidents problem on Moodle, in the Lab 11 PB 4 section. | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | </onlydft> | ||
+ | <!-- ======================================================================================== | ||
+ | SOLUTION PROGRAMS | ||
+ | ======================================================================================== --> | ||
+ | <showafterdate after="20180423 12:00" before="20180601 00:00"> | ||
+ | |||
+ | =Solution Programs= | ||
+ | <br /> | ||
+ | ==genericCar.py== | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | |||
+ | 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 ) | ||
+ | |||
+ | </source> | ||
+ | ==manyCars.py== | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # 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() | ||
+ | |||
+ | </source> | ||
+ | =Solution Programs= | ||
+ | ==Animals == | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # 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() | ||
+ | |||
+ | |||
+ | </source> | ||
+ | <br /> | ||
+ | ==Aquarium== | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | # 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() | ||
+ | </source> | ||
+ | <br /> | ||
+ | == Presidents== | ||
+ | <br /> | ||
+ | ::<source lang="python"> | ||
+ | # 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() | ||
+ | |||
+ | |||
+ | </source> | ||
+ | |||
+ | |||
+ | </showafterdate> | ||
+ | <br /> | ||
+ | <br /> | ||
+ | [[Category:CSC111]][[Category:Python]][[Category:Homework]] |
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">
Contents
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>