All exercises from Downey, Allen. Think Python. Green Tea Press, 2014. http://www.greenteapress.com/thinkpython/
In [ ]:
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
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)
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."""
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()
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()