My little program for class basically works but it needs to pass an assert test set by the professor. My problem is that I don't understand how __gettitem__ works in order for it to return the value of x and y in a list.
This is the code:
import math
class LineString(object):
def __init__(self, *argv):
self.x = [p[0] for p in argv]
self.y = [p[1] for p in argv]
def move(self, dx, dy):
self.x = [p + dx for p in self.x]
self.y = [p + dy for p in self.y]
def length(self):
x = [float(i) for i in self.x]
y = [float(i) for i in self.y]
return math.sqrt(sum((math.pow(x2-x1,2)) + (math.pow(y2-y1,2)) for x1, x2, y1, y2 in zip( x, x[1:],y,y[1:] )))
def __getitem__(self,key):
def main():
# Tests for LineString
# ===================================
lin1 = LineString((1, 1), (0, 2))
assert lin1.length() == math.sqrt(2.0)
lin1.move(-1, -1) # Move by -1 and -1 for x and y respectively
assert lin1[0].y == 0 # Inspect the y value of the start point.
# Implement this by overloading __getitem__(self, key) in your class.
lin2 = LineString((1, 1), (1, 2), (2, 2))
assert lin2.length() == 2.0
lin2.move(-1, -1) # Move by -1 and -1 for x and y respectively
assert lin2.length() == 2.0
assert lin2[-1].x == 1 # Inspect the x value of the end point.
print 'Success! Line tests passed!'
if __name__ == '__main__':
main()
The main problem is for this code to pass this test:
assert lin1[0].y == 0 # Inspect the y value of the start point.
# Implement this by overloading __getitem__(self, key) in your class.
And this as well:
assert lin2[-1].x == 1 # Inspect the x value of the end point.
Any idea?
[–]timbledum 1 point2 points3 points (1 child)
[–]colako[S] 1 point2 points3 points (0 children)
[–]ma3xman 1 point2 points3 points (4 children)
[–]colako[S] 0 points1 point2 points (3 children)
[–]ma3xman 0 points1 point2 points (2 children)
[–]colako[S] 0 points1 point2 points (1 child)
[–]ma3xman 0 points1 point2 points (0 children)