Advertisement
nux95

[Cython] Permutation implementation

Aug 9th, 2011
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. cpdef permutation_atindex(int _int, object _set, length):
  2.     """
  3.    Return the permutation at index '_int' for itemgetter '_set'
  4.    with length 'length'.
  5.    """
  6.  
  7.     # c-type declaration
  8.     cdef int strLength, index
  9.     cdef list items     = []
  10.  
  11.     # c-assignment
  12.     strLength   = len(_set)
  13.     index       = _int % strLength
  14.     items.append(_set[index])
  15.  
  16.     for n from 1 <= n < length:
  17.         _int  //= strLength
  18.         index   = _int % strLength
  19.         items.append(_set[index])
  20.  
  21.     return items
  22.  
  23. cdef class PermutationIterator:
  24.     """
  25.    A class that can iterate over possible permuations
  26.    of the given 'iterable' and 'length' argument.
  27.    """
  28.  
  29.     cpdef int current, max, length
  30.     cpdef object iterable
  31.  
  32.     def __init__(self, object iterable, int length):
  33.         self.length     = length
  34.         self.current    = 0
  35.         self.max        = len(iterable) ** length
  36.         self.iterable   = iterable
  37.  
  38.     def __iter__(self):
  39.         return self
  40.  
  41.     def __next__(self):
  42.         if self.current >= self.max:
  43.             raise StopIteration
  44.  
  45.         try:
  46.             return permutation_atindex(self.current, self.iterable, self.length)
  47.         finally:
  48.             self.current   += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement