All exercises from Downey, Allen. Think Python. Green Tea Press, 2014. http://www.greenteapress.com/thinkpython/

Exercise 1 (Wendy)


In [ ]:

Exercise 2 (Sarah)


In [1]:
class Point(object):
    """Represents a point in 2-D space."""
    
class Rectangle(object):
    """Represents a rectangle.
    attributes: width, height, corner.
    """

box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
    
def move_rectangle(rect,dx,dy):
    
    rect.corner.x = rect.corner.x + dx
    rect.corner.y = rect.corner.y + dy

move_rectangle(box, 50,100)
print box.corner.x
print box.corner.y


50.0
100.0

Exercise 3 (Liu)


In [3]:
import math
import copy

class Point():
    """Represents a point in 2-D space."""
    
def print_point(p):
    print '(%g, %g)' % (p.x, p.y)    
    
class Rectangle(object):
    """Represents a rectangle.
    attributes: width, height, corner.
    """

def move_rectangle(b, dx, dy):
    b.corner.x += dx
    b.corner.y += dy
     
def deep_move_retangle(b, dx, dy):
    new_box = copy.deepcopy(b)
    move_rectangle(new_box, dx, dy)
    return new_box

box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0

print box
print box.corner
print_point(box.corner)
move_rectangle(box, 10, 10)
print box
print box.corner
print_point(box.corner)
moved_box = deep_move_retangle(box, 10, 10)
print moved_box
print moved_box.corner
print_point(moved_box.corner)


<__main__.Rectangle object at 0x104999650>
<__main__.Point instance at 0x1045097a0>
(0, 0)
<__main__.Rectangle object at 0x104999650>
<__main__.Point instance at 0x1045097a0>
(10, 10)
<__main__.Rectangle object at 0x10450a610>
<__main__.Point instance at 0x104509680>
(20, 20)

Exercise 4 (Dan)


In [1]:
from swampy.World import World

class Point(object):
    """Represents a point in 2-D space."""
    
class Rectangle(object):
    """Represents a rectangle. 

    attributes: width, height, corner."""

Part 1 + 2


In [ ]:
def draw_rectangle(canvas, rectangle):
    lowerleft = [rectangle.corner.x, rectangle.corner.y]
    topright = [rectangle.corner.x + rectangle.width,
                rectangle.corner.y + rectangle.height]
    bbox = [lowerleft, topright]
    canvas.rectangle(bbox, outline='black', width=2, fill=rectangle.color)

r = Rectangle()
r.width = 100.0
r.height = 200.0
r.corner = Point()
r.corner.x = 0.0
r.corner.y = 0.0
r.color = 'yellow'

world = World()
canvas = world.ca(width=500, height=500, background='white')
draw_rectangle(canvas, r)
world.mainloop()

Part 3


In [4]:
def draw_point(canvas, point):
    canvas.circle([point.x, point.y], 2, outline=None, fill='black')

p = Point()
p.x = 10
p.y =50
world = World()
canvas = world.ca(width=500, height=500, background='white')
draw_point(canvas, p)
world.mainloop()

Part 4

Part 5