python - 在任何维度(Python)中生成单位超立方体的功能
问题描述
我需要编写一个 python 函数,该函数根据将放置在左上角的起始坐标返回单位超立方体的坐标列表或元组(正方形/框/正方体等)。我有一个向量类,它采用任意长度的列表,用于项目的不同不相关部分。点的顺序并不重要,只是起始位置是“最低点”,即 [x, y, z ...] 并且没有其他点是 [x-1, y] 或类似的东西那。它需要适用于任意数量的维度,并且每一边都是一个单位长。
对于正方形,它看起来像这样:
def square(x, y):
return [
Vector([x, y]),
Vector([x + 1, y]),
Vector([x + 1, y + 1]),
Vector([x, y + 1])
]
立方体看起来像这样:
def cube(x, y, z):
return [
Vector([x, y, z]),
Vector([x + 1, y, z]),
Vector([x + 1, y + 1, z]),
Vector([x, y + 1, z]),
Vector([x, y, z + 1]),
Vector([x + 1, y, z + 1]),
Vector([x + 1, y + 1, z + 1]),
Vector([x, y + 1, z + 1]),
]
它一直这样,所以我需要编写一个看起来像这样的函数:
def hypercube(start):
points = [];
#Add all the points to the list (need to figure out)
return points
# And it will be used like so:
starts = [35, 12]
print(hypercube(starts))
# result:
#[Vector(35, 12), Vector(36, 12), Vector(36, 13), Vector(35, 13)]
starts = [35, 12, 34, 17, 2]
print(hypercube(starts))
#result :
#[Vector(35, 12, 34, 17, 2), ... Vector(36, 13, 35, 18, 3)]
我知道可能有一种递归方式可以做到这一点,我只是想不出。
解决方案
该itertools
函数combinations_with_replacement
可以为您的立方体中的每个轴提供所有需要的“加 1”或“不加”组合。
所以,假设你的Vector
类支持向量加法:
from itertolls import combinations_with_replacements
from ... import Vector
def hypercube(starts):
dimensions = len(starts)
return [starts + Vector(*combination) for combination in combinations_with_replacements((0, 1), dimensions)]
如果您的“向量”还不支持使用+
运算符进行加法,您所要做的就是为其添加一个__add__
方法:
class Vector:
def __add__(self, other):
return self.__class__([comp1 + comp2 for comp1, comp2 in zip(self, other)])
(在这种情况下,假设您的“Vector”继承自 Python 序列,如列表或 collections.abc.Sequence 并且可以正确迭代 - 否则,只需传递zip
包含序列数据的 Vector 属性)
推荐阅读
- css - 如何使用引导程序设置自定义 joomla 组件的样式
- jquery - 使用 jquery ajax 更新部分视图中的表
- c - 如何在函数中将指针作为参数传递?
- node.js - 在 Visual Studio Code 中,如何在 launch.json 中传递参数
- json - JSON 数组格式,无列名
- bash - 如何在 GitHub 操作中推送 nuget 包
- image - OpenCV 和 Matlab 之间的像素值略有不同
- java - 如何序列化 java.security.Principal?
- flutter - 颤振构建:构建失败
- python - 在python中实例化和继承多个类