在任意维度生成单位超立方体的函数 (Python)

Funtion to Generate a Unit hypercube in any Dimesion (Python)

我需要编写一个 python 函数,该函数 returns 单位超立方体的坐标列表或元组,(square/box/tesseract 等)基于将要放置的起始坐标在左上角。我有一个向量 class,它包含一个任意长度的列表,我将其用于项目的不同不相关部分。点的顺序并不重要,只是起始位置是 'lowest point',即 [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 可以为您的立方体中的每个轴提供所有需要的 "add 1" 或 "add nothing" 组合。

因此,假设您的 Vector class 支持向量加法:

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)]

如果您的 "Vector" 还不支持使用 + 运算符进行加法, 您所要做的就是向其中包含一个 __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保存序列数据的向量属性)