4 ms·
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:/
by jpfr 11y ago
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.product https://docs.python.org/2/library/itertools.html#itertools.p...
- elcritch 11y ago`itertools` comes in real handy in some cases. I just wish it didn't require a special import. Have you used the itertools.partition much? It's pretty handy as well. 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-generated-functions-c80e240e05f3#.ji8w9kehh https://medium.com/@acidflask/smoothing-data-with-julia-s-ge...) but it looks cool!
- clickok 11y agoIt'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.