Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- cpdef permutation_atindex(int _int, object _set, length):
- """
- Return the permutation at index '_int' for itemgetter '_set'
- with length 'length'.
- """
- # c-type declaration
- cdef int strLength, index
- cdef list items = []
- # c-assignment
- strLength = len(_set)
- index = _int % strLength
- items.append(_set[index])
- for n from 1 <= n < length:
- _int //= strLength
- index = _int % strLength
- items.append(_set[index])
- return items
- cdef class PermutationIterator:
- """
- A class that can iterate over possible permuations
- of the given 'iterable' and 'length' argument.
- """
- cpdef int current, max, length
- cpdef object iterable
- def __init__(self, object iterable, int length):
- self.length = length
- self.current = 0
- self.max = len(iterable) ** length
- self.iterable = iterable
- def __iter__(self):
- return self
- def __next__(self):
- if self.current >= self.max:
- raise StopIteration
- try:
- return permutation_atindex(self.current, self.iterable, self.length)
- finally:
- self.current += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement