在Python中寻找坐标系中某些点之间的最短路径

2024-05-26

我编写了一个代码,可以在坐标系中的特定宽度和长度范围内生成所需数量的点。它计算并列出我使用欧几里德方法生成的这些点的距离矩阵。

我的代码在这里:

import pandas as pd
from scipy.spatial import distance_matrix, distance

import random

npoints = int(input("Type the npoints:"))
width = float(input("Enter the Width you want:"))
height = float(input("Enter the Height you want:"))

sample = []
for _ in range(npoints):
    sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')

mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)

输出是:

Type the npoints:5
Enter the Width you want:6
Enter the Height you want:7
(3.25, 3.55), (5.51, 6.47), (5.87, 5.31), (2.27, 3.20), (0.96, 3.83)
          0         1         2         3         4
0  0.000000  3.690201  3.153510  1.047022  2.305800
1  3.690201  0.000000  1.209096  4.608588  5.257688
2  3.153510  1.209096  0.000000  4.176733  5.123103
3  1.047022  4.608588  4.176733  0.000000  1.450613
4  2.305800  5.257688  5.123103  1.450613  0.000000

Process finished with exit code 0

我想创建一种算法,从输入的随机点开始,绕过最短路径中的所有点。 (最近邻法继续根据欧几里得距离找到离起始点最近的点,然后去未纠缠点中距离这个新点最近的点。这个过程一直持续到遍历完所有点,完成一轮)。我怎样才能在 10 个不同的点重复这个过程 10 次并得到如下输出:

Tour Number:1
Number of points visited in order in the relevant round: 0-7-3-8-2...
Total route length of the tour: 18,75755

Tour Number:2
The number of the points visited in order in the relevant round: 6-9-11-2-7...
Total route length of the tour: 14,49849
.
...

非常感谢您的帮助。


如果我正确理解你的问题,这应该可以完成单个路径的工作。

import random
import pandas as pd
from scipy.spatial import distance_matrix, distance

npoints = int(input("Type the npoints: "))
width = float(input("Enter the Width you want: "))
height = float(input("Enter the Height you want: "))

sample = []
for _ in range(npoints):
    sample.append((width * random.random(), height * random.random()))
print(*[f"({w:.2f}, {h:.2f})" for w, h in sample], sep=', ')

mat_dist = distance.cdist(sample, sample, 'euclidean')
df_mat_dist = pd.DataFrame(mat_dist)
print(df_mat_dist)

#Randomly select the first point
closest_idx = random.randrange(npoints)
path_points = [closest_idx]

#Find the closest point to the starting point, different from diagonal and save results
path_length = 0

for _ in range(npoints-1):
    closest_dist = df_mat_dist.loc[closest_idx, ~df_mat_dist.index.isin(path_points)].min()
    closest_idx = df_mat_dist.loc[closest_idx, ~df_mat_dist.index.isin(path_points)].idxmin()
    path_points.append(closest_idx)
    path_length += closest_dist

print(path_points, path_length)

Output

Type the npoints: 5
Enter the Width you want: 6
Enter the Height you want: 7
(2.45, 6.66), (3.01, 3.94), (5.06, 0.51), (5.89, 1.04), (1.37, 5.03)
          0         1         2         3         4
0  0.000000  2.775327  6.677550  6.587089  1.950042
1  2.775327  0.000000  3.993631  4.086550  1.970787
2  6.677550  3.993631  0.000000  0.988898  5.834766
3  6.587089  4.086550  0.988898  0.000000  6.030719
4  1.950042  1.970787  5.834766  6.030719  0.000000
[1, 4, 0, 3, 2] 11.49681560383563

由此您应该能够调整代码以运行 10 次。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Python中寻找坐标系中某些点之间的最短路径 的相关文章

  • 具有日期变量的 SSIS For 循环容器

    我想创建一个每月包 在 ODBC 上执行每日查询并写入输出文件 更具体地说 必须首先在上个月的第一天执行查询 e g 01 11 2018 然后下一个 02 11 2018 直到上个月的最后一天 30 11 2018 日期变量当前保存为字符
  • 良好的类似 STL 的 C 库 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 对于具有向量 双端队列 堆栈 哈希图 树形图 集合等数据结构的 C 语言来说 有哪些好的库 请使用纯 C 并且与平台无关 The Glib
  • Python 的键盘中断不会中止 Rust 函数 (PyO3)

    我有一个使用 PyO3 用 Rust 编写的 Python 库 它涉及一些昂贵的计算 单个函数调用最多需要 10 分钟 从 Python 调用时如何中止执行 Ctrl C 好像只有执行结束后才会处理 所以本质上没什么用 最小可重现示例 Ca
  • 将 saxon 与 python 结合使用

    我需要使用 python 处理 XSLT 目前我正在使用仅支持 XSLT 1 的 lxml 现在我需要处理 XSLT 2 有没有办法将 saxon XSLT 处理器与 python 一起使用 有两种可能的方法 设置一个 HTTP 服务 接受
  • 通过最小元素比较对 5 个元素进行排序

    我必须在 python 中使用元素之间的最小比较次数来建模对 5 个元素的列表进行排序的执行计划 除此之外 复杂性是无关紧要的 结果是一个对的列表 表示在另一时间对列表进行排序所需的比较 我知道有一种算法可以通过 7 次比较 总是在元素之间
  • Flask 会话变量

    我正在用 Flask 编写一个小型网络应用程序 当两个用户 在同一网络下 尝试使用应用程序时 我遇到会话变量问题 这是代码 import os from flask import Flask request render template
  • 如何替换 pandas 数据框列中的重音符号

    我有一个数据框dataSwiss其中包含瑞士城市的信息 我想用普通字母替换带有重音符号的字母 这就是我正在做的 dataSwiss Municipality dataSwiss Municipality str encode utf 8 d
  • 测试 python Counter 是否包含在另一个 Counter 中

    如何测试是否是pythonCounter https docs python org 2 library collections html collections Counter is 包含在另一个中使用以下定义 柜台a包含在计数器中b当且
  • 绘制方程

    我正在尝试创建一个函数 它将绘制我告诉它的任何公式 import numpy as np import matplotlib pyplot as plt def graph formula x range x np array x rang
  • BeautifulSoup 中的嵌套标签 - Python

    我在网站和 stackoverflow 上查看了许多示例 但找不到解决我的问题的通用解决方案 我正在处理一个非常混乱的网站 我想抓取一些数据 标记看起来像这样 table tbody tr tr tr td td td table tr t
  • 添加不同形状的 numpy 数组

    我想添加两个不同形状的 numpy 数组 但不进行广播 而是将 缺失 值视为零 可能最简单的例子是 1 2 3 2 gt 3 2 3 or 1 2 3 2 1 gt 3 2 3 1 0 0 我事先不知道形状 我正在弄乱每个 np shape
  • Python 的“zip”内置函数的 Ruby 等价物是什么?

    Ruby 是否有与 Python 内置函数等效的东西zip功能 如果不是 做同样事情的简洁方法是什么 一些背景信息 当我试图找到一种干净的方法来进行涉及两个数组的检查时 出现了这个问题 如果我有zip 我可以写这样的东西 zip a b a
  • 在Python中获取文件描述符的位置

    比如说 我有一个原始数字文件描述符 我需要根据它获取文件中的当前位置 import os psutil some code that works with file lp lib open path to file p psutil Pro
  • 无法在 Python 3 中导入 cProfile

    我试图将 cProfile 模块导入 Python 3 3 0 但出现以下错误 Traceback most recent call last File
  • Pandas:merge_asof() 对多行求和/不重复

    我正在处理两个数据集 每个数据集具有不同的关联日期 我想合并它们 但因为日期不完全匹配 我相信merge asof 是最好的方法 然而 有两件事发生merge asof 不理想的 数字重复 数字丢失 以下代码是一个示例 df a pd Da
  • Fabric env.roledefs 未按预期运行

    On the 面料网站 http docs fabfile org en 1 10 usage execution html 给出这个例子 from fabric api import env env roledefs web hosts
  • 对年龄列进行分组/分类

    我有一个数据框说df有一个柱子 Ages gt gt gt df Age 0 22 1 38 2 26 3 35 4 35 5 1 6 54 我想对这个年龄段进行分组并创建一个像这样的新专栏 If age gt 0 age lt 2 the
  • 有没有办法检测正在运行的代码是否正在上下文管理器内执行?

    正如标题所述 有没有办法做到这样的事情 def call back if called inside context print running in context else print called outside context 这将
  • 导入错误:没有名为 site 的模块 - mac

    我已经有这个问题几个月了 每次我想获取一个新的 python 包并使用它时 我都会在终端中收到此错误 ImportError No module named site 我不知道为什么会出现这个错误 实际上 我无法使用任何新软件包 因为每次我
  • Python Selenium:如何在文本文件中打印网站上的值?

    我正在尝试编写一个脚本 该脚本将从 tulsaspca org 网站获取以下 6 个值并将其打印在 txt 文件中 最终输出应该是 905 4896 7105 23194 1004 42000 放置的动物 的 HTML span class

随机推荐