首页 > 解决方案 > 在任何维度(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)]

我知道可能有一种递归方式可以做到这一点,我只是想不出。

标签: pythonmultidimensional-cube

解决方案


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 属性)


推荐阅读