Skip to main content
 首页 » 编程设计

python之如何使用python查找线段的长度

2024年09月07日7qq78292959

我想使用 Python 计算(任意数量的)线段的长度。我使用了以下代码,但我遇到元组不能将减法作为操作数。我怎样才能克服它?我想知道我是否错过了任何重要的 Python 概念。

from itertools import starmap 
import math 
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,*args): # A method with any number of arguments, args 
 
        self.args=[Point(*args) for p in args] # A list of Points 
 
    def length(self): 
        pairs=zip(self.args, self.args[1:]) 
        return sum(starmap(distance,pairs)) 
 
def distance(p1, p2): 
    a = p1.x,p1.y 
    b = p2.x,p2.y 
 
    print (math.sqrt((a[0]-b[0])**2-(a[1]-b[1])**2)) 
    # calculates distance between two given points p1 and p2 
    return math.sqrt((a** 2)+ (b** 2)) 
 
 
if __name__ == '__main__': 
    # Tests for LineString 
    # =================================== 
    lin1 = LineString((1, 1), (0, 2)) 
 
    assert lin1.length() == 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!') 

请您参考如下方法:

如前所述,它必须是 Point(*p) 而不是 Point(*args)。后者会将所有点元组传递给每个点的构造函数。不过,您还必须修复距离。

def __init__(self, *args): 
    self.args=[Point(*p) for p in args] 
 
def distance(p1, p2): 
    return math.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2) 

但是,不是创建您自己的 Point 类,而是内置了一个您可以使用的“重要 Python 概念”complex numbers ,使 distance 更简单:

def __init__(self, *args): 
    self.args=[complex(*p) for p in args] 
 
def distance(p1, p2): 
    return abs(p1 - p2)