2025-12-26 21:12:54 +0300 MSK
Iterator for Combination
Links
Code
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self._length: int = combinationLength
self._chars: str = characters
self._cur: list[str] = []
self._gen = self._generator(0)
self._nxt: Optional[str] = next(self._gen, None)
def _generator(self, i: int) -> Generator[str, None, None]:
if len(self._cur) == self._length:
yield "".join(self._cur)
return
if i >= len(self._chars):
return
char = self._chars[i]
self._cur.append(char)
yield from self._generator(i + 1)
self._cur.pop()
yield from self._generator(i + 1)
def next(self) -> str:
nxt = self._nxt
self._nxt = next(self._gen, None)
return nxt
def hasNext(self) -> bool:
return self._nxt is not None
# Your CombinationIterator object will be instantiated and called as such:
# obj = CombinationIterator(characters, combinationLength)
# param_1 = obj.next()
# param_2 = obj.hasNext()