Skip to content

Commit de6192f

Browse files
authored
Create iterator-for-combination.py
1 parent 0a8f7e4 commit de6192f

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

Python/iterator-for-combination.py

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Time: O(k), per operation
2+
# Space: O(k)
3+
4+
import itertools
5+
6+
7+
class CombinationIterator(object):
8+
9+
def __init__(self, characters, combinationLength):
10+
"""
11+
:type characters: str
12+
:type combinationLength: int
13+
"""
14+
self.__it = itertools.combinations(characters, combinationLength)
15+
self.__curr = None
16+
self.__last = characters[-combinationLength:]
17+
18+
def next(self):
19+
"""
20+
:rtype: str
21+
"""
22+
self.__curr = "".join(self.__it.next())
23+
return self.__curr
24+
25+
def hasNext(self):
26+
"""
27+
:rtype: bool
28+
"""
29+
return self.__curr != self.__last
30+
31+
32+
# Time: O(k), per operation
33+
# Space: O(k)
34+
import functools
35+
36+
37+
class CombinationIterator2(object):
38+
39+
def __init__(self, characters, combinationLength):
40+
"""
41+
:type characters: str
42+
:type combinationLength: int
43+
"""
44+
self.__characters = characters
45+
self.__combinationLength = combinationLength
46+
self.__it = self.__iterative_dfs()
47+
self.__curr = None
48+
self.__last = characters[-combinationLength:]
49+
50+
def __iterative_dfs(self):
51+
def conquer():
52+
if len(curr) == self.__combinationLength:
53+
return curr
54+
55+
def prev_divide(c):
56+
curr.append(c)
57+
58+
def divide(i):
59+
if len(curr) != self.__combinationLength:
60+
for j in reversed(xrange(i, len(self.__characters)-(self.__combinationLength-len(curr)-1))):
61+
stk.append(functools.partial(post_divide))
62+
stk.append(functools.partial(divide, j+1))
63+
stk.append(functools.partial(prev_divide, self.__characters[j]))
64+
stk.append(functools.partial(conquer))
65+
66+
def post_divide():
67+
curr.pop()
68+
69+
curr = []
70+
stk = [functools.partial(divide, 0)]
71+
while stk:
72+
result = stk.pop()()
73+
if result is not None:
74+
yield result
75+
76+
def next(self):
77+
"""
78+
:rtype: str
79+
"""
80+
self.__curr = "".join(next(self.__it))
81+
return self.__curr
82+
83+
def hasNext(self):
84+
"""
85+
:rtype: bool
86+
"""
87+
return self.__curr != self.__last
88+
89+
90+
# Your CombinationIterator object will be instantiated and called as such:
91+
# obj = CombinationIterator(characters, combinationLength)
92+
# param_1 = obj.next()
93+
# param_2 = obj.hasNext()

0 commit comments

Comments
 (0)