[英]Find the order of points with the distance between each point
I'm coding a program that finds the order of three (can be more) points on a linear line using the distance between the points.我正在编写一个程序,该程序使用点之间的距离在一条直线上找到三个(可以更多)点的顺序。
For example, if the input is a .txt file as below:例如,如果输入是一个 .txt 文件,如下所示:
A,A,0
A,B,57
A,C,43
B,B,0
B,C,100
C,C,0
The output should be:输出应该是:
['B','A','C']
I am having a hard time finding an algorithm that would make this work.我很难找到一种算法来完成这项工作。 It would be of so much help if you guys can give me some insight.
如果你们能给我一些见解,那将是非常有帮助的。
This is a generic solution that should work for any number of points:这是一个通用的解决方案,应该适用于任意数量的点:
distance_input = """A,A,0
A,B,57
A,C,43
B,B,0
B,C,100
C,C,0"""
# Convert the input string to more sane data structures
distances = {tuple(sorted(s.split(",")[:2])): int(s.split(",")[-1]) for s in distance_input.splitlines()}
point_list = [s.split(",")[0] for s in distance_input.splitlines()]
points = {}
# The min (or max) is one of the points in the pair that has the highest distance
max_distance = max(distances.items(), key=lambda t: t[1])
min_point = max_distance[0][0]
points[min_point] = 0
# Calculate remaining values using their distances from 0
for point in point_list:
points[point] = distances[tuple(sorted([point, min_point]))]
ordering = [p for p, v in sorted(points.items(), key=lambda t: t[1])]
print(ordering)
This will print这将打印
['B', 'A', 'C']
First, let's get the distance between A and B, A and C, and B and C, as that's what interests us.首先,让我们得到 A 和 B、A 和 C、B 和 C 之间的距离,因为这是我们感兴趣的。
filename = "text.txt" # Change this to the name of your file
file = open("file.txt", "r")
lines = file.readLines()
for line in lines: # Read every line in the file one by one
data = line.split(",") # Separate the line by comma
# data[0] is the first point, data[1] is the second, and data[2] is the distance
if data[0] == "A" and data[1] == "B":
a_to_b = int(data[2])
elif data[0] == "A" and data[1] == "C":
a_to_c = int(data[2])
elif data[0] == "B" and data[1] == "C":
b_to_c = int(data[2])
Next, you can use that to figure out the order of the points:接下来,您可以使用它来确定点的顺序:
if a_to_b == a_to_c + b_to_c:
order = ["A", "C", "B"]
elif a_to_c == a_to_b + b_to_c:
order = ["A", "B", "C"]
elif b_to_c == a_to_b + a_to_c:
order = ["B", "A", "C"]
Finally, close the file:最后,关闭文件:
file.close()
This only works for 3 points, but hopefully it can get you started.这仅适用于 3 分,但希望它可以帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.