行と列でn
by matrixを指定n
すると、隣接するすべての値を循環スパイラルで反復処理したいと思います。M
i
j
これを行うポイントは、M に依存する関数 をテストしてf
、 から離れた半径を見つける(i, j)
ことf
ですTrue
。したがって、f
次のようになります。
def f(x, y):
"""do stuff with x and y, and return a bool"""
次のように呼び出されます。
R = numpy.zeros(M.shape, dtype=numpy.int)
# for (i, j) in M
for (radius, (cx, cy)) in circle_around(i, j):
if not f(M[i][j], M[cx][cy]):
R[cx][cy] = radius - 1
break
circle_around
循環スパイラルのインデックス (へのイテレータ) を返す関数はどこにありますか。したがって、 のすべての点についてM
、このコードは をf
返すその点からの半径を計算して格納しますTrue
。
を計算するより効率的な方法があればR
、私もそれを受け入れます。
アップデート:
回答を提出してくれたすべての人に感謝します。circle_around
イテレータからの出力をプロットして、イテレータが何をするかを示す短い関数を作成しました。回答を更新するか、新しい回答を投稿する場合は、このコードを使用してソリューションを検証できます。
from matplotlib import pyplot as plt
def plot(g, name):
plt.axis([-10, 10, -10, 10])
ax = plt.gca()
ax.yaxis.grid(color='gray')
ax.xaxis.grid(color='gray')
X, Y = [], []
for i in xrange(100):
(r, (x, y)) = g.next()
X.append(x)
Y.append(y)
print "%d: radius %d" % (i, r)
plt.plot(X, Y, 'r-', linewidth=2.0)
plt.title(name)
plt.savefig(name + ".png")
結果は次のとおり
plot(circle_around(0, 0), "F.J")
です。
plot(circle_around(0, 0, 10), "WolframH")
:
マグネシウムの提案を次のようにコーディングしました。
def circle_around_magnesium(x, y):
import math
theta = 0
dtheta = math.pi / 32.0
a, b = (0, 1) # are there better params to use here?
spiral = lambda theta : a + b*theta
lastX, lastY = (x, y)
while True:
r = spiral(theta)
X = r * math.cos(theta)
Y = r * math.sin(theta)
if round(X) != lastX or round(Y) != lastY:
lastX, lastY = round(X), round(Y)
yield (r, (lastX, lastY))
theta += dtheta
plot(circle_around(0, 0, 10), "magnesium")
:
ご覧のとおり、私が探しているインターフェイスを満たす結果はどれも、0、0 の周りのすべてのインデックスをカバーする円形のらせんを生成していません。注文。