FaC*_*fee 5 python combinations list
计算(x, y)
平面中两点之间距离的公式是公知且直截了当的.
但是,解决n
点问题的最佳方法是什么,您想要计算平均距离?
例:
import matplotlib.pyplot as plt
x=[89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0]
y=[78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0]
plt.scatter(x, y,color='k')
plt.show()
Run Code Online (Sandbox Code Playgroud)
距离简单地呈现为:
import math
dist=math.sqrt((x2-x1)**2+(y2-y1)**2)
Run Code Online (Sandbox Code Playgroud)
但这是一个不允许重复组合的问题.怎么接近它?
Ste*_*ski 10
itertools.combinations
给出没有重复的组合:
>>> for combo in itertools.combinations([(1,1), (2,2), (3,3), (4,4)], 2):
... print(combo)
...
((1, 1), (2, 2))
((1, 1), (3, 3))
((1, 1), (4, 4))
((2, 2), (3, 3))
((2, 2), (4, 4))
((3, 3), (4, 4))
Run Code Online (Sandbox Code Playgroud)
您的问题代码:
import math
from itertools import combinations
def dist(p1, p2):
(x1, y1), (x2, y2) = p1, p2
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
x = [89.86, 23.0, 9.29, 55.47, 4.5, 59.0, 1.65, 56.2, 18.53, 40.0]
y = [78.65, 28.0, 63.43, 66.47, 68.0, 69.5, 86.26, 84.2, 88.0, 111.0]
points = list(zip(x,y))
distances = [dist(p1, p2) for p1, p2 in combinations(points, 2)]
avg_distance = sum(distances) / len(distances)
Run Code Online (Sandbox Code Playgroud)