更新了Martin的解决方案(非常感谢)。想知道如何通过组合在LineString类中使用move方法。请查看为完成代码而需要传递的断言。任何进一步的指导将非常感谢。
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
class LineString(object):
def __init__(self, *points):
self.points = [Point(*point) for point in points]
def length(self):
pairs = zip(self.points, self.points[1:])
return sum(starmap(distance, pairs))
def distance(p1, p2):
return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)
if __name__ == '__main__':
# Tests for LineString
# ===================================
lin1 = LineString((1, 1), (0, 2))
assert lin1.length() == sqrt(2.0)
lin1.move(-1, -1) # Help with Composition needed
assert lin1[0].y == 0 # Inspect the y value of the start point.
lin2 = LineString((1, 1), (1, 2), (2, 2))
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.
答案 0 :(得分:0)
您发布的代码的更简洁和有效版本
from itertools import starmap
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
self.x += dx
self.y += dy
class LineString:
def __init__(self, *points):
self.points = [Point(*point) for point in points]
def length(self):
pairs = zip(self.points, self.points[1:])
return sum(starmap(distance, pairs))
def distance(p1, p2):
return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)
测试
import numpy as np
points = np.arange(20).reshape((-1, 2))
ls = LineString(*points)
ls.length()
返回25.455 = sqrt(8)* 9,这是正确的。