ちょうど対応するであろう(すべてゼロの組み合わせを廃棄するように注意しながら、現在のものに対してインデックスを形成するNに{1、-1、0}の組のCartesian powerを反復処理する必要があります可能であれば、必要に応じて遅延評価することができることに注意してください。デカルト力は、非再帰的な方法で実装することができます。
algorithm cartesian_power(s : set, N : positive integer)
result := list(empty list)
repeat N times
result_step= empty list
for res in result do
for elem in s do
new_res := append(res, s)
result_step := append(result_step, new_res)
loop
loop
result := result_step
loop
return result
ます。また、このアルゴリズムをレイジー評価することができ、あなたが最後の反復で作成された要素を生成しなければならないので、それはもう少し複雑だが、最も外側のループの
これらのアルゴリズムでは、インデックスの境界や他の制約などは考慮されていないため、ケースに応じてロジックを追加する必要がありますが、コアの考え方は同じです。ここで
は、Pythonのジェネレータとして実装例である:私はデカルトの電力を計算するためにPythonの組み込み関数を使用していますので、
from itertools import product
def neighbors(index):
N = len(index)
for relative_index in product((-1, 0, 1), repeat=N):
if not all(i == 0 for i in relative_index):
yield tuple(i + i_rel for i, i_rel in zip(index, relative_index))
print(list(neighbors((1, 2)))
>>> [(0, 1), (0, 2), (0, 3), (1, 1), (1, 3), (2, 1), (2, 2), (2, 3)]
print(list(neighbors((1, 2, 3)))
>>> [(0, 1, 2),
(0, 1, 3),
(0, 1, 4),
(0, 2, 2),
(0, 2, 3),
(0, 2, 4),
(0, 3, 2),
(0, 3, 3),
(0, 3, 4),
(1, 1, 2),
(1, 1, 3),
(1, 1, 4),
(1, 2, 2),
(1, 2, 4),
(1, 3, 2),
(1, 3, 3),
(1, 3, 4),
(2, 1, 2),
(2, 1, 3),
(2, 1, 4),
(2, 2, 2),
(2, 2, 3),
(2, 2, 4),
(2, 3, 2),
(2, 3, 3),
(2, 3, 4)]
はもちろん、私はここに浮気しています。しかし、the documentation of itertools.product
に行くと、上で書いたアルゴリズムのPython実装が見えます。
再帰を試してから、コードにどれくらい手を入れたかを教えてください – cahen
各次元を 'index - 1'から' index + 1'までループすることができます。ただし、毎回*少なくとも1つのインデックスがゼロでないことを確認する必要があります。これは、すべての要素を取り出すために 'O(3 * d)'と比較して、 'd'が次元の数である' O(d * 3^d) 'の高価な複雑さを持っています。 – meowgoesthedog