Difference between revisions of "CSC111 Homework 10 2011"
(→Problem 4) |
(→Your assignment) |
||
Line 268: | Line 268: | ||
==Your assignment== | ==Your assignment== | ||
* My cat ate my program! Yes, it did! I had a nicely written (though not documented) program, was ready to show it to you, but my cat ate part of it. | * My cat ate my program! Yes, it did! I had a nicely written (though not documented) program, was ready to show it to you, but my cat ate part of it. | ||
− | * The good part is that I kept a copy of | + | * The good part is that I kept a copy of the program's output when it was still in its complete state: |
<code><pre> | <code><pre> | ||
Line 440: | Line 440: | ||
<br /> | <br /> | ||
* Figure out what is missing so that the output of your program matches '''exactly''' the output shown above. | * Figure out what is missing so that the output of your program matches '''exactly''' the output shown above. | ||
+ | |||
==Submisstion== | ==Submisstion== | ||
* call your program '''hw10d.py''' and submit it as illustrated in Problem 1 above. | * call your program '''hw10d.py''' and submit it as illustrated in Problem 1 above. |
Revision as of 17:05, 29 November 2011
--D. Thiebaut 12:41, 29 November 2011 (EST)
This is an A/E type of homework. You have several problems to solve. You either get an A or an E on each one. What is important here is Python, not documentation or robustness (this is an exception to the rule). You have to solve different problems and make your program output the correct answer. Correct answers get A, incorrect ones get E. I will not read the code closely and take point for lack of documentation, and I will not try to make your program crash to test its robustness.
The main goal for this particular assignment is for you to use classes and objects and make them work.
This assignment is due Tuesday evening, Dec. 6, at midnight.
Contents
Problem 1
- Modify the car class we saw in class (some code available on the class Web page), and make the class contain
- a rectangle for the body,
- a rectangle for the cab part,
- a rectangle (or rectangles) for the window (or windows),
- a Text caption in the middle of the body (s.a. "Taxi" ),
- and a move() method, so that we can make the car move out of the screen with this loop:
for i in range( 500 ): car.move( 2, 0 );
- (we assume that car is an object instantiated from the class Car.)
- Make your program implement this loop so that we can see the car move out of the window.
- Store your program in a file called hw10a.py and submit it this way:
rsubmit hw10 hw10a.py (if you are working on beowulf)
- or use the http://cs.smith.edu/~111a/submit10.htm submit form.
Problem 2
- Play with the program below:
from graphics import *
class Ball:
def __init__(self, c, r ):
self.c = Circle( c, r )
self.dx = 0
self.dy = 0
def draw( self, win ):
self.c.draw( win )
def setFill( self, col ):
self.c.setFill( col )
def setDirection( self, dx, dy ):
self.dx = dx
self.dy = dy
def move( self ):
self.c.move( self.dx, self.dy )
def main():
width = 800
height = 600
win = GraphWin( "111a-xx HW10", width, height )
b1 = Ball( Point( width/4, height/2 ), 10 )
b1.setFill( "blue" )
b1.setDirection( 1, 2 )
b1.draw( win )
b2 = Ball( Point( width/4, height/2 ), 10 )
b2.setFill( "green" )
b2.setDirection( 2, 1 )
b2.draw( win )
while True:
b1.move()
b2.move()
if win.checkMouse() != None:
break
win.close()
main()
- It's not documented, but for this homework documentation is not required.
- Note how each ball remembers its direction of movement in the two member variables self.dx and self.dy.
Assignment
- Add a new method (or more if that makes your code simpler) to the Ball class called changeDirIfHittingWall(). This method changes the sign self.dx or self.dy when the ball hits a vertical or horizontal wall (the boundaries of the window).
- If your method is written correctly, the main function below will see the balls bouncing off all the windows borders in a natural fashion, in a way similar to what we have done many times before.
def main():
width = 800
height = 600
win = GraphWin( "111a-xx HW10", width, height )
b1 = Ball( Point( width/4, height/2 ), 10 )
b1.setFill( "blue" )
b1.setDirection( 1, 2 )
b1.draw( win )
b2 = Ball( Point( width/4, height/2 ), 10 )
b2.setFill( "green" )
b2.setDirection( 2, 1 )
b2.draw( win )
while True:
b1.move()
b2.move()
if win.checkMouse() != None:
break
b1.changeDirIfHittingWall( width, height )
b2.changeDirIfHittingWall( width, height )
win.close()
Additional Information
- the balls must bounce off all four borders of the window
- the balls do not have to bounce off each other
Submission
- Call your program hw10b.py and submit it as indicated in Problem 1 above.
Problem 3
- And you thought we were done with the presidents!
- Play with the code below:
presidents = \
"""Presidency ,President ,Wikipedia Entry,Took office ,Left office ,Party ,Portrait,Thumbnail,Home State
1,George Washington,http://en.wikipedia.org/wiki/George_Washington,30/04/1789,4/03/1797,Independent ,GeorgeWashington.jpg,thmb_GeorgeWashington.jpg,Virginia
2,John Adams,http://en.wikipedia.org/wiki/John_Adams,4/03/1797,4/03/1801,Federalist ,JohnAdams.jpg,thmb_JohnAdams.jpg,Massachusetts
3,Thomas Jefferson,http://en.wikipedia.org/wiki/Thomas_Jefferson,4/03/1801,4/03/1809,Democratic-Republican ,Thomasjefferson.gif,thmb_Thomasjefferson.gif,Virginia
4,James Madison,http://en.wikipedia.org/wiki/James_Madison,4/03/1809,4/03/1817,Democratic-Republican ,JamesMadison.gif,thmb_JamesMadison.gif,Virginia
5,James Monroe,http://en.wikipedia.org/wiki/James_Monroe,4/03/1817,4/03/1825,Democratic-Republican ,JamesMonroe.gif,thmb_JamesMonroe.gif,Virginia
6,John Quincy Adams,http://en.wikipedia.org/wiki/John_Quincy_Adams,4/03/1825,4/03/1829,Democratic-Republican/National Republican ,JohnQuincyAdams.gif,thmb_JohnQuincyAdams.gif,Massachusetts
7,Andrew Jackson,http://en.wikipedia.org/wiki/Andrew_Jackson,4/03/1829,4/03/1837,Democratic ,Andrew_jackson_head.gif,thmb_Andrew_jackson_head.gif,Tennessee
8,Martin Van Buren,http://en.wikipedia.org/wiki/Martin_Van_Buren,4/03/1837,4/03/1841,Democratic ,MartinVanBuren.gif,thmb_MartinVanBuren.gif,New York
9,William Henry Harrison,http://en.wikipedia.org/wiki/William_Henry_Harrison,4/03/1841,4/04/1841,Whig,WilliamHenryHarrison.gif,thmb_WilliamHenryHarrison.gif,Ohio
10,John Tyler,http://en.wikipedia.org/wiki/John_Tyler,4/04/1841,4/03/1845,Whig,JohnTyler.jpg,thmb_JohnTyler.jpg,Virginia
11,James K. Polk,http://en.wikipedia.org/wiki/James_K._Polk,4/03/1845,4/03/1849,Democratic ,JamesKPolk.gif,thmb_JamesKPolk.gif,Tennessee
12,Zachary Taylor,http://en.wikipedia.org/wiki/Zachary_Taylor,4/03/1849,9/07/1850,Whig,ZacharyTaylor.jpg,thmb_ZacharyTaylor.jpg,Louisiana
13,Millard Fillmore,http://en.wikipedia.org/wiki/Millard_Fillmore,9/07/1850,4/03/1853,Whig,MillardFillmore.png,thmb_MillardFillmore.png,New York
14,Franklin Pierce,http://en.wikipedia.org/wiki/Franklin_Pierce,4/03/1853,4/03/1857,Democratic ,FranklinPierce.gif,thmb_FranklinPierce.gif,New Hampshire
15,James Buchanan,http://en.wikipedia.org/wiki/James_Buchanan,4/03/1857,4/03/1861,Democratic ,JamesBuchanan.gif,thmb_JamesBuchanan.gif,Pennsylvania
16,Abraham Lincoln,http://en.wikipedia.org/wiki/Abraham_Lincoln,4/03/1861,15/04/1865,Republican/National Union,AbrahamLincoln.jpg,thmb_AbrahamLincoln.jpg,Illinois
17,Andrew Johnson,http://en.wikipedia.org/wiki/Andrew_Johnson,15/04/1865,4/03/1869,Democratic/National Union,AndrewJohnson.gif,thmb_AndrewJohnson.gif,Tennessee
18,Ulysses S. Grant,http://en.wikipedia.org/wiki/Ulysses_S._Grant,4/03/1869,4/03/1877,Republican ,UlyssesSGrant.gif,thmb_UlyssesSGrant.gif,Ohio
19,Rutherford B. Hayes,http://en.wikipedia.org/wiki/Rutherford_B._Hayes,4/03/1877,4/03/1881,Republican ,RutherfordBHayes.png,thmb_RutherfordBHayes.png,Ohio
20,James A. Garfield,http://en.wikipedia.org/wiki/James_A._Garfield,4/03/1881,19/09/1881,Republican ,James_Garfield.jpg,thmb_James_Garfield.jpg,Ohio
21,Chester A. Arthur,http://en.wikipedia.org/wiki/Chester_A._Arthur,19/09/1881,4/03/1885,Republican ,ChesterAArthur.gif,thmb_ChesterAArthur.gif,New York
22,Grover Cleveland,http://en.wikipedia.org/wiki/Grover_Cleveland,4/03/1885,4/03/1889,Democratic ,Grover_Cleveland_2.jpg,thmb_Grover_Cleveland_2.jpg,New York
23,Benjamin Harrison,http://en.wikipedia.org/wiki/Benjamin_Harrison,4/03/1889,4/03/1893,Republican ,BenjaminHarrison.gif,thmb_BenjaminHarrison.gif,Indiana
24,Grover Cleveland,http://en.wikipedia.org/wiki/Grover_Cleveland,4/03/1893,4/03/1897,Democratic ,Grover_Cleveland.jpg,thmb_Grover_Cleveland.jpg,New York
25,William McKinley,http://en.wikipedia.org/wiki/William_McKinley,4/03/1897,14/9/1901,Republican ,WilliamMcKinley.gif,thmb_WilliamMcKinley.gif,Ohio
26,Theodore Roosevelt,http://en.wikipedia.org/wiki/Theodore_Roosevelt,14/9/1901,4/3/1909,Republican ,TheodoreRoosevelt.jpg,thmb_TheodoreRoosevelt.jpg,New York
27,William Howard Taft,http://en.wikipedia.org/wiki/William_Howard_Taft,4/3/1909,4/03/1913,Republican ,WilliamHowardTaft.jpg,thmb_WilliamHowardTaft.jpg,Ohio
28,Woodrow Wilson,http://en.wikipedia.org/wiki/Woodrow_Wilson,4/03/1913,4/03/1921,Democratic ,WoodrowWilson.gif,thmb_WoodrowWilson.gif,New Jersey
29,Warren G. Harding,http://en.wikipedia.org/wiki/Warren_G._Harding,4/03/1921,2/8/1923,Republican ,WarrenGHarding.gif,thmb_WarrenGHarding.gif,Ohio
30,Calvin Coolidge,http://en.wikipedia.org/wiki/Calvin_Coolidge,2/8/1923,4/03/1929,Republican ,CoolidgeWHPortrait.gif,thmb_CoolidgeWHPortrait.gif,Massachusetts
31,Herbert Hoover,http://en.wikipedia.org/wiki/Herbert_Hoover,4/03/1929,4/03/1933,Republican ,HerbertHover.gif,thmb_HerbertHover.gif,Iowa
32,Franklin D. Roosevelt,http://en.wikipedia.org/wiki/Franklin_D._Roosevelt,4/03/1933,12/4/1945,Democratic,FranklinDRoosevelt.gif,thmb_FranklinDRoosevelt.gif,New York
33,Harry S. Truman,http://en.wikipedia.org/wiki/Harry_S._Truman,12/4/1945,20/01/1953,Democratic,HarryTruman.jpg,thmb_HarryTruman.jpg,Missouri
34,Dwight D. Eisenhower,http://en.wikipedia.org/wiki/Dwight_D._Eisenhower,20/01/1953,20/01/1961,Republican ,Dwight_D_Eisenhower.jpg,thmb_Dwight_D_Eisenhower.jpg,Texas
35,John F. Kennedy,http://en.wikipedia.org/wiki/John_F._Kennedy,20/01/1961,22/11/1963,Democratic,John_F_Kennedy.jpg,thmb_John_F_Kennedy.jpg,Massachusetts
36,Lyndon B. Johnson,http://en.wikipedia.org/wiki/Lyndon_B._Johnson,22/11/1963,20/1/1969,Democratic,Lyndon_B_Johnson.gif,thmb_Lyndon_B_Johnson.gif,Texas
37,Richard Nixon,http://en.wikipedia.org/wiki/Richard_Nixon,20/1/1969,9/8/1974,Republican,RichardNixon.gif,thmb_RichardNixon.gif,California
38,Gerald Ford,http://en.wikipedia.org/wiki/Gerald_Ford,9/8/1974,20/01/1977,Republican,Gerald_R_Ford.jpg,thmb_Gerald_R_Ford.jpg,Michigan
39,Jimmy Carter,http://en.wikipedia.org/wiki/Jimmy_Carter,20/01/1977,20/01/1981,Democratic ,James_E_Carter.gif,thmb_James_E_Carter.gif,Georgia
40,Ronald Reagan,http://en.wikipedia.org/wiki/Ronald_Reagan,20/01/1981,20/01/1989,Republican ,ReaganWH.jpg,thmb_ReaganWH.jpg,California
41,George H. W. Bush,http://en.wikipedia.org/wiki/George_H._W._Bush,20/01/1989,20/01/1993,Republican ,George_H_W_Bush.gif,thmb_George_H_W_Bush.gif,Texas
42,Bill Clinton,http://en.wikipedia.org/wiki/Bill_Clinton,20/01/1993,20/01/2001,Democratic ,Clinton.jpg,thmb_Clinton.jpg,Arkansas
43,George W. Bush,http://en.wikipedia.org/wiki/George_W._Bush,20/01/2001,20/01/2009,Republican ,George_W_Bush.jpg,thmb_George_W_Bush.jpg,Texas
44,Barack Obama, http://en.wikipedia.org/wiki/Barack_Obama,20/01/2009,Incumbent , Democratic ,Barack_Obama.jpg,thmb_Barack_Obama.jpg,Illinois"""
class President:
""" A class for one president. Holds all the info relative to a president as strings"""
def __init__( self, n, name, url, dateIn, dateOut, party, pic, thumb, state ):
self.n = n
self.name = name
self.url = url
self.dateIn = dateIn
self.dateOut = dateOut
self.party = party
self.pic = pic
self.thumb = thumb
self.state = state
def isDemocrat( self ):
return self.party.lower().find( "democ" ) != -1
def isRepublican( self ):
return self.party.lower().find( "republi" ) != -1
def is3rdParty( self ):
return not self.isDemocrat() and not self.isRepublican()
def toString( self ):
party = ""
if self.isDemocrat(): party = "D"
if self.isRepublican(): party += "R"
if self.is3rdParty(): party = "Other"
return "%s: %30s(%s) %s-%s from %s" % \
( self.n, self.name, party, self.dateIn, self.dateOut, self.state )
def createListOfPres( text ):
"""parses the text containing the CSV list of presidents and returns a list of
president objects, or an empty list if nothing could be read"""
try:
lines = text.split( '\n' )[1:]
except (IndexError ):
return []
prez = []
for line in lines:
try:
n, name, url, dateIn, dateOut, party, pic, thumb, state = line.split( ',' )
except (ValueError,NameError):
continue
# create president object and add it to the list prez
prez.append( President( n, name, url, dateIn, dateOut, party, pic, thumb, state ) )
# return the list of president objects
return prez
def main():
# get a list of objects, each one a president
prez = createListOfPres( presidents )
# print each president without url or image info.
for p in prez:
print( p.toString() )
main()
Your assignment
Part 1
- For this part you cannot modify the President class.
- You can only modify the main() function.
- Whatever you do, you cannot use the string presidents again: its purpose is to be split into a list of objects, which the function createListOfPres() does...
- Make the main program output the number of democratic presidents, the number of republican presidents, and the number of "other" party presidents.
Part 2
- For this part you can add new methods to the President class.
- You cannot go back to the string presidents.
- Make your program prompt the user for a year, and output the president or presidents who was/were in active duties that year.
- It is fine if your program does not output Obama for 2011, but it is nice if it does!
Submission
- Store your program in a file called hw10c.py and submit it as illustrated in Problem 1 above.
Problem 4
Your assignment
- My cat ate my program! Yes, it did! I had a nicely written (though not documented) program, was ready to show it to you, but my cat ate part of it.
- The good part is that I kept a copy of the program's output when it was still in its complete state:
Cheetah 70.0 mph
Pronghorn Antelope 61.0 mph
Wildebeest 50.0 mph
Lion 50.0 mph
Thomson's Gazelle 50.0 mph
Quarter Horse 47.5 mph
Elk 45.0 mph
Cape Hunting Dog 45.0 mph
Coyote 43.0 mph
Gray Fox 42.0 mph
Hyena 40.0 mph
Zebra 40.0 mph
Mongolian Wild Ass 40.0 mph
Greyhound 39.4 mph
Whippet 35.5 mph
Rabbit (domestic) 35.0 mph
Mule Deer 35.0 mph
Jackal 35.0 mph
Reindeer 32.0 mph
Giraffe 32.0 mph
White-Tailed Deer 30.0 mph
Warthog 30.0 mph
Grizzly Bear 30.0 mph
Cat (domestic) 30.0 mph
Human 27.9 mph
Elephant 25.0 mph
Black Mamba Snake 20.0 mph
Six-Lined Racerunner 18.0 mph
Wild Turkey 15.0 mph
Squirrel 12.0 mph
Pig (domestic) 11.0 mph
Chicken 9.0 mph
Spider (Tegenaria atrica) 1.2 mph
Giant Tortoise 0.2 mph
Three-Toed Sloth 0.1 mph
Garden Snail 0.0 mph
Fastest animal: Cheetah
Slowest animal: Garden Snail
Closest to 0 miles/hour: Garden Snail 0.03 mph
Closest to 3 miles/hour: Spider (Tegenaria atrica) 1.17 mph
Closest to 6 miles/hour: Chicken 9 mph
Closest to 9 miles/hour: Chicken 9 mph
Closest to 12 miles/hour: Squirrel 12 mph
Closest to 15 miles/hour: Wild Turkey 15 mph
Closest to 18 miles/hour: Six-Lined Racerunner 18 mph
Closest to 21 miles/hour: Black Mamba Snake 20 mph
Closest to 24 miles/hour: Elephant 25 mph
Closest to 27 miles/hour: Human 27.89 mph
Closest to 30 miles/hour: Cat (domestic) 30 mph
Closest to 33 miles/hour: Giraffe 32 mph
Closest to 36 miles/hour: Whippet 35.5 mph
Closest to 39 miles/hour: Greyhound 39.35 mph
Closest to 42 miles/hour: Gray Fox 42 mph
Closest to 45 miles/hour: Cape Hunting Dog 45 mph
Closest to 48 miles/hour: Quarter Horse 47.5 mph
- Unfortunately all I can reassemble from the pieces of paper I could get back from the tiger's claws is this:
animalSpeed = """Cheetah 70
Pronghorn Antelope 61
Wildebeest 50
Lion 50
Thomson's Gazelle 50
Quarter Horse 47.5
Elk 45
Cape Hunting Dog 45
Coyote 43
Gray Fox 42
Hyena 40
Zebra 40
Mongolian Wild Ass 40
Greyhound 39.35
Whippet 35.5
Rabbit (domestic) 35
Mule Deer 35
Jackal 35
Reindeer 32
Giraffe 32
White-Tailed Deer 30
Warthog 30
Grizzly Bear 30
Cat (domestic) 30
Human 27.89
Elephant 25
Black Mamba Snake 20
Six-Lined Racerunner 18
Wild Turkey 15
Squirrel 12
Pig (domestic) 11
Chicken 9
Spider (Tegenaria atrica) 1.17
Giant Tortoise 0.17
Three-Toed Sloth 0.15
Garden Snail 0.03"""
class AnimalList:
def __init__( self ):
self.List = []
def append( self, animal, speed):
self.List.append( [ ] )
def get( self, index ):
if 0 <= index < len( self.List ):
speed, animal = self.List[ index ]
return animal, speed
return None, None
def size( self ):
return len( self.List )
def sort( self ):
...
def reverse( self ):
self.List.reverse()
def getFastest( self ):
self.sort()
if len( self.List )> 0:
speed, animal = self.List[ -1 ]
return animal, speed
return None, None
def topN( self, n ):
return self.List[-n: ]
def closestInSpeedTo( self, targetSpeed ):
if len( self.List )==0:
return None, None
closestSpeed, closestAnimal = self.List[0]
for speed, animal in self.List:
if abs( targetSpeed - closestSpeed ) > abs( targetSpeed - speed ):
closestSpeed = speed
closestAnimal = animal
return closestAnimal, closestSpeed
def main():
animals = AnimalList()
for line in animalSpeed.split( '\n' ):
words = line.split()
speed =
animal =
animals.append( animal, speed )
for i in range( animals.size() ):
animal, speed = animals.get( i )
print( "%30s %10.1f mph" % (animal, speed ) )
animal, speed = animals.getSlowest()
print( "Slowest animal: ", animal )
for target in range( 0, 50, 3 ):
animal, speed = animals.closestInSpeedTo( target )
print( "Closest to", target," miles/hour:", animal, speed, "mph" )
main()
- Figure out what is missing so that the output of your program matches exactly the output shown above.
Submisstion
- call your program hw10d.py and submit it as illustrated in Problem 1 above.