【问题标题】:Generate random points and generating a path for it生成随机点并为其生成路径
【发布时间】:2021-07-14 20:42:06
【问题描述】:

我想在 x,y 散点图上生成 10 个不同的点,并且会有一条路径可以通过每个点并返回起点。

import random
import matplotlib.pyplot as plt

num_points = 10
x1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
xy1 = [x1,y1]

plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.show()

结果:scatterplot of 10 points

目标:this was done via paint

【问题讨论】:

  • 有什么限制?没有限制——>意大利面条线。没有交叉线->您可以使用基于角度的简单算法。最短路径 --> 这是 NP 难的,称为 Travelling Salesman Problem

标签: python python-3.x


【解决方案1】:

尝试做

plt.plot(x1,y1)

这个解决方案来自this 线程,我会在我的机器上尝试一下。

编辑:这不会连接端点。改为这样做:

import random
import matplotlib.pyplot as plt

num_points = 10
x1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
xy1 = [x1,y1]


plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.plot(x1,y1,c='blue')
plt.plot([x1[0],x1[-1]],[y1[0],y1[-1]],c='blue') #connects first and last point
plt.plot(x2,y2,c='red')
plt.plot([x2[0],x2[-1]],[y2[0],y2[-1]],c='red') #connects first and last point in second set

plt.show()  

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2019-05-31
    • 2018-02-15
    • 1970-01-01
    • 2017-12-11
    • 2011-09-05
    相关资源
    最近更新 更多