3 ms·
It's always nice to get a chance to deploy some functional techniques. You can get a Cartesian range (also called a von Neumann neighborhood) of size "n" and d
by clickok 11y ago
It's always nice to get a chance to deploy some functional techniques.
You can get a Cartesian range (also called a von Neumann neighborhood) of size "n" and dimension "d" via:
def cartesian_range(n, d):
return product(*[range(-n, n+1) for _ in range(d)])
This returns a generator that yields all tuples of integers where each integer has absolute value less than or equal to "n". If you want the Moore neighborhood (tuples whose absolute sum is less than or equal to "n"), you can add a filtering step:
def moore_neighborhood(n, d):
seq = product(*[range(-n, n+1) for _ in range(d)])
return filter(lambda x: sum(map(abs, x)) <= n, seq)
There's probably a more efficient way of doing this for Moore neighborhoods, but I didn't come across it when I was looking into such things.
The problem lies in the fact that as "d" grows large, you're throwing away more and more of "seq", so while it looks elegant, you might need something a little less terse in practice.