Python has itertools.product to iterate over the cartesian product of two lists.
Some of the most elegant code I ever wrote is due to this abstraction.
https://docs.python.org/2/library/itertools.html#itertools.p...
https://docs.python.org/2/library/itertools.html#itertools.p...
The fun part with Julia is the ability to use these style of for-loops to generate code to run arbitrary N-dimensional computations based on the specific input array sizes. Not sure exactly what they're doing [here](https://medium.com/@acidflask/smoothing-data-with-julia-s-ge...) but it looks cool!
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.