Dan*_*nko 1 python coordinates
我的任务有问题。根据问题的条件,给出了具有 xyz 坐标的两个点 p1、p2,您需要使用该类求出这些点在 3D 空间中的距离。看起来任务本身很简单,但对我来说困难在于距离的计算必须使用只有一个距离(其他)参数的方法来进行,而我不\xe2\x80\x99不明白这是怎么回事如果需要两个变量就可以完成,这两个变量将给出两个点的坐标,并且在该方法中我们只能使用一个。
\n我尝试这样做,但出现错误(不支持的操作数类型 -:'str' 和 'str'):
\nfrom math import sqrt\n\n\nclass Point3D:\n x: float\n y: float\n z: float\n\n def __init__(self, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n\n @staticmethod\n def distance(other):\n return sqrt((other[0][0] - other[1][0]) ** 2 + (other[0][1] - other[1][1]) ** 2 + (other[0][2] - other[1][2]) ** 2)\n\np1 = [1, 2, 3]\np2 = [3, 2, 1]\ns1 = Point3D(*p1)\ns2 = Point3D(*p2)\nprint(Point3D.distance((s1, s2)))\n\n>>>unsupported operand type(s) for -: 'str' and 'str'\nRun Code Online (Sandbox Code Playgroud)\n我也尝试这样做,但它给出了一个错误(“str”对象没有属性“x”)
\n# The rest of the code is the same\n\n@staticmethod\n def distance(other):\n return sqrt((other[0].x - other[1].x) ** 2 + (other[0].y - other[1].y) ** 2 + (other[0].z - other[1].z) ** 2)\n\np1 = [1, 2, 3]\np2 = [3, 2, 1]\ns1 = Point3D(*p1)\ns2 = Point3D(*p2)\nprint(Point3D.distance((s1, s2)))\n\n>>>AttributeError: 'str' object has no attribute 'x'\nRun Code Online (Sandbox Code Playgroud)\n还有可以正常工作但不被接受的代码,因为距离需要 2 个参数,但需要 1 个(这是他们不\xe2\x80\x99t 接受我的代码的示例):
\n# The rest of the code is the same\n\n def distance(self, other):\n return sqrt((other.x1 - self.x1) ** 2 + (other.y1 - self.y1) ** 2 + (other.z1 - self.z1) ** 2)\n \np1 = [1, 2, 3]\np2 = [3, 2, 1]\npoint1 = Point3D(*p1)\npoint2 = Point3D(*p2)\nprint(point1.distance(point2))\n\n>>>2.8284271247461903\nRun Code Online (Sandbox Code Playgroud)\n请帮助我修复代码,以便它与距离(其他)方法一起使用并且不会抛出错误。如果需要,您可以删除@staticmethod。老实说,我不知道该怎么办了。我会很高兴得到任何帮助
\n您的代码和错误不匹配。
当我尝试编写代码时,会导致以下异常:
TypeError: 'Point3D' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
这是可以理解的,因为Point3D不是序列类型。
此外,您在远程调用中有无关的括号,因此您基本上只给它一个参数(一个二元组)。
尝试这个:
from math import sqrt
class Point3D:
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
def distance(self, p2):
return sqrt((self.x - p2.x) ** 2 + (self.y - p2.y) ** 2 + (self.z - p2.z) ** 2)
s1 = Point3D(1, 2, 3)
s2 = Point3D(3, 2, 1)
print(s1.distance(s2))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
817 次 |
| 最近记录: |