python - Python 3.x - 计算绘图&&计算坐标系中可能的正方形
问题描述
所以,现在,我有一个坐标系,如:
. . .
. . .
(x=0, y=0) (x=1, y=0) (x=2, y=0)
(x=0, y=1) (x=1, y=1) (x=2, y=1)
我们知道有 3 个可能的矩形要绘制。
我们知道每个元素的坐标。(在左上角它的 0,0 (x,y))(在右下角它的 2,1 (x,y))
我们知道一个矩形有 4 个点,现在,它的:(x, y), (x2, y), (x, y2), (x2, y2) 所以,
(x, y) (x2, y)
(x, y2) (x2, y2)
我们知道矩形的面积大于 0,所以x != x2 && y != y2
.
我们知道(在示例坐标系中)三个可绘制矩形坐标是:
1,
0,0 1,0
0,1 1,1
2,
1,0 2,0
1,1 2,1
3,
0,0 2,0
0,1 2,1
现在,菱形不在游戏中。
那么,如何在 Python 中获得解决方案(我希望解决方案是可绘制矩形的坐标。)?有人可以给我一个代码或说明吗?我在互联网上找不到任何东西。当然,它必须使用具有更多坐标的坐标系。
我只在寻找 Python 代码。
解决方案
下面是一种非常简单但贪婪的计算和输出给定坐标系中矩形数量的方法。
首先,定义一个函数来检查四个点是否形成一个矩形:
def is_rectangle(a, b, c, d):
# sort coordinates
a, b, c, d = sorted([a, b, c, d])
# check rectangle
return a[0] == b[0] and c[0] == d[0] and a[1] == c[1] and b[1] == d[1]
然后,一个函数来计算坐标系中所有可能的四点组合中的矩形:
def number_rectangles(coordinates):
# output the number of rectangles
return sum([is_rectangle(a, b, c, d) for (a, b, c, d) in itertools.combinations(coordinates, 4)])
最后,输出这些矩形坐标的方法是:
def get_rectangles(coordinates):
# return each rectangle
return [[a, b, c, d] for (a, b, c, d) in itertools.combinations(coordinates, 4) if is_rectangle(a, b, c, d)]
你会得到你的例子是:
coordinates = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
number_rectangles(coordinates)
# > 3
get_rectangles(coordinates)
# > [[(0, 0), (0, 1), (1, 0), (1, 1)],
# > [(0, 0), (0, 2), (1, 0), (1, 2)],
# > [(0, 1), (0, 2), (1, 1), (1, 2)]]
推荐阅读
- vb.net - 按名称循环文本框
- python - 在 Python 数据框中选择列时出错
- html - 创建一个没有固定布局的 HTML 表格,设置了最大宽度,并且行不换行但有溢出:隐藏
- java - 什么是“未解决的编译问题”?
- python - 使用 pika 为 RabbitMQ 确认消息
- shopify - Translation API 自动将文本内容翻译成不同的语言?
- python - 如何将文本边界框与 pyplot.Rectangle 对齐?
- python - 导入类的问题
- java - Spring boot - Couchbase AbstractCouchbaseConfiguration - 如何避免覆盖不必要的方法
- c# - 如何将字符串“text1”设置为包含项目 text1、text2、test3 的组合框?