Weekly Graded Assignment (13)
The starter code below contains a Point class. Add a method slopeFromOrigin
, which returns the slope of the line joining the origin to the point. For example,
>>> Point(4, 10).slopeFromOrigin()
2.5
>>> Point(12, -3).slopeFromOrigin()
-0.25
>>> Point(-6, 0).slopeFromOrigin()
0
The equation for calculating slope between any two points is slope = (Y2 - Y1) / (X2 - X1). Remember that dividing by 0 is not allowed, so there are some inputs that will cause your method to fail. Return None when that happens.
class Point:
""" Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
""" Create a new point at the given coordinates. """
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
# TODO define a method called slopeFromOrigin here
def slopeFromOrigin(self):
if self.x == 0:
return None
else:
return self.y / self.x
# some tests to check your code
from test import testEqual
testEqual( Point(4, 10).slopeFromOrigin(), 2.5 )
testEqual( Point(5, 10).slopeFromOrigin(), 2 )
testEqual( Point(0, 10).slopeFromOrigin(), None )
testEqual( Point(20, 10).slopeFromOrigin(), 0.5 )
testEqual( Point(20, 20).slopeFromOrigin(), 1 )
testEqual( Point(4, -10).slopeFromOrigin(), -2.5 )
testEqual( Point(-4, -10).slopeFromOrigin(), 2.5 )
testEqual( Point(-6, 0).slopeFromOrigin(), 0 )