SageMath:创建一个任意维度的向量列表,范围从 -a 到 +a

SageMath: Creating a list of vectors of an arbitrary dimension ranging from -a to +a

我想创建一个任意维度的向量列表 n,这样它们的所有条目的范围都是从输入 -aa。我知道如何针对给定维度执行此操作。例如,如果 n=2,则执行以下操作:

a = 1
[vector([x,y]) for x in [-a..a] for y in [-a..a]]

#output:
[(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]

我不确定如何将其扩展为任意 n。我使用了列表理解,但它可以用任何其他格式来完成。想到的一个想法,但没有奏效,是使用类似的东西:

n = 2
letters = [chr(ord('`')+i+23) for i in [1..n]]

# output
# ['x', 'y']

a = 1
[vector([var(letters[0]),var(letters[1])]) for var(letters[0]) in [-a..a] for var(letters[1]) in [-a..a]]

# SyntaxError: can't assign to function call

在 SageMath 中是否有一种有效的方法来执行此操作?

您可以为此使用 itertools.product

import itertools as it


def all_coords(a: int, ndim: int):
    yield from it.product(range(-a + 1, a), repeat=ndim)

用法:

>>> list(all_coords(2, ndim=2))
[(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 0), (0, 1), (1, -1), (1, 0), (1, 1)]
>>> list(all_coords(3, ndim=2))
[(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2), (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2), (0, -2), (0, -1), (0, 0), (0, 1), (0, 2), (1, -2), (1, -1), (1, 0), (1, 1), (1, 2), (2, -2), (2, -1), (2, 0), (2, 1), (2, 2)]
>>> list(all_coords(2, ndim=3))
[(-1, -1, -1), (-1, -1, 0), (-1, -1, 1), (-1, 0, -1), (-1, 0, 0), (-1, 0, 1), (-1, 1, -1), (-1, 1, 0), (-1, 1, 1), (0, -1, -1), (0, -1, 0), (0, -1, 1), (0, 0, -1), (0, 0, 0), (0, 0, 1), (0, 1, -1), (0, 1, 0), (0, 1, 1), (1, -1, -1), (1, -1, 0), (1, -1, 1), (1, 0, -1), (1, 0, 0), (1, 0, 1), (1, 1, -1), (1, 1, 0), (1, 1, 1)]