After I have shortly succeed in writing a minimalistic Python3.6 extension module in C++ ( see here ) I plan to provide a Python module which does the same as the following Python function iterUniqueCombos()
:
def iterUniqueCombos(lstOfSortableItems, sizeOfCombo):
lstOfSortedItems = sorted(lstOfSortableItems)
sizeOfList = len(lstOfSortedItems)
lstComboCandidate = []
def idxNextUnique(idxItemOfList):
idxNextUniqueCandidate = idxItemOfList + 1
while (
idxNextUniqueCandidate < sizeOfList
and
lstOfSortedItems[idxNextUniqueCandidate] == lstOfSortedItems[idxItemOfList]
): # while
idxNextUniqueCandidate += 1
idxNextUnique = idxNextUniqueCandidate
return idxNextUnique
def combinate(idxItemOfList):
if len(lstComboCandidate) == sizeOfCombo:
yield tuple(lstComboCandidate)
elif sizeOfList - idxItemOfList >= sizeOfCombo - len(lstComboCandidate):
lstComboCandidate.append(lstOfSortedItems[idxItemOfList])
yield from combinate(idxItemOfList + 1)
lstComboCandidate.pop()
yield from combinate(idxNextUnique(idxItemOfList))
yield from combinate(0)
I have some basic understanding of Python and C++ programming, but absolutely no idea how to "translate" Pythons yield into C++ code of an Python extension module. So my question is:
How to write C++ code (of a Python module) able to return a Python iterator object?
Any hints to get me started are welcome.
UPDATE (status 2017-05-07):
Both the comment: yield has no C++ equivalent. I'd start by implementing the iterator protocol manually in Python, to get out of the yield and yield from mindset. – user2357112 Apr 26 at 1:16 and the hint in the answer by danny
the answer to this question is the same as asking 'How do I implement an iterator without using yield' but in a C++ extension instead of pure Python. put my programming efforts in the wrong direction of reinventing the wheel by rewriting the algorithms code in order to eliminate yield
and by writing the C-code of a Python extension module from scratch (what resulted in raining Segmentation Fault
errors).
The state-of-the-art of my current knowledge on the subject of the question is that using Cython it is possible to translate the above Python code (which is using
yield
) directly into C code of a Python extension module.
This is not only possible using the Python code just as it is (without the need of rewriting anything), but in addition to that the speed of the extension module created by Cython from the algorithm using yield
runs at least twice that fast as the extension module created from the to an iterator class using __iter__
and __next__
rewritten algorithm (the latter is valid if no Cython specific speed optimization code is added to the Python script).