Skip to content

Instantly share code, notes, and snippets.

@zed
Created March 12, 2012 04:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zed/2019680 to your computer and use it in GitHub Desktop.
Save zed/2019680 to your computer and use it in GitHub Desktop.
#file: next_permutation.pyx
from libcpp cimport bool
cimport numpy as np
ctypedef np.int_t dtype_t
cdef extern from "<algorithm>" namespace "std":
bool cpp_next_permutation "std::next_permutation" (dtype_t* first, dtype_t* last)
def next_permutation(np.ndarray[dtype_t,ndim=1] a):
cdef dtype_t* first = <dtype_t *>a.data
return cpp_next_permutation(first, first + a.shape[0])
#file: next_permutation.pyxbld
from distutils.extension import Extension
def make_ext(modname, pyxfilename):
return Extension(name=modname,
sources=[pyxfilename],
language="c++")
#file: test_next_permutation.py
import numpy as np
import pyximport; pyximport.install()
from next_permutation import next_permutation
# see http://stackoverflow.com/a/9660395
groups = [(1,2),(3,4,5),(6,7)]
groupdxs = [i for i, group in enumerate(groups) for j in range(len(group))]
a = np.ascontiguousarray(groupdxs, dtype=np.int)
while True:
iters = [iter(group) for group in groups]
print [next(iters[i]) for i in a]
if not next_permutation(a):
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment