Skip to content

Instantly share code, notes, and snippets.

@uchida
Created May 20, 2011 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchida/982701 to your computer and use it in GitHub Desktop.
Save uchida/982701 to your computer and use it in GitHub Desktop.
a portable and compact version of numpy.ndindex
import functools, operator
prod = functools.partial(functools.reduce, operator.mul)
def ndindex(maxvals):
total = prod(maxvals)
index = [0] * len(maxvals)
for _ in range(total):
yield tuple(index)
for i, n in enumerate(reversed(maxvals)):
index[-i-1] += 1
if index[-i-1] < n:
break
else:
index[-i-1] = 0
raise StopIteration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment