-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathfreq_iterator.py
92 lines (77 loc) · 2.25 KB
/
freq_iterator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Testing:
>>> gotcha = []
>>> for _in, _out in (
... (
... ['foo', 'foo', 'bar', 'foo'],
... [['foo', 2], ['bar', 1], ['foo', 1]]
... ),
... (
... ['a', 'a', 'a', 'b', 'b', 'c', 'a', 'b', 'b'],
... [['a', 3], ['b', 2], ['c', 1], ['a', 1], ['b', 2]]
... ),
... (
... ['a', 'a', 'a', 'b', 'b', 'c', 'a', 'b', 'c'],
... [['a', 3], ['b', 2], ['c', 1], ['a', 1], ['b', 1], ['c', 1]]
... ),
... (
... ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'],
... [['a', 1], ['b', 1], ['c', 1],
... ['d', 1], ['e', 1], ['f', 1],
... ['g', 1], ['h', 1], ['i', 1]]
... ),
... ):
... origin_iterator = ListIterator(_in)
... res = [origin_iterator.next() for _ in range(len(_in))]
... if _in != res: print(_in, res)
... gotcha.append(_in == res)
... gotcha.append(origin_iterator.has_next() is False)
... gotcha.append(origin_iterator.next() is None)
...
... res = []
... origin_iterator = ListIterator(_in)
... freq_iterator = FreqIterator(origin_iterator)
... while freq_iterator.has_next():
... res.append(freq_iterator.next())
...
... if res != _out: print(_in, res)
... gotcha.append(res == _out)
>>> bool(gotcha) and all(gotcha)
True
"""
class FreqIterator:
def __init__(self, iterator):
if not iterator or not iterator.has_next():
return
self.iterator = iterator
self.pre = None
self.word = iterator.next()
def next(self):
if not self.has_next():
return
cnt = 1
nxt = None
while self.iterator.has_next():
nxt = self.iterator.next()
if nxt != self.word:
break
cnt += 1
self.pre = self.word
self.word = nxt
return [self.pre, cnt]
def has_next(self):
return self.pre != self.word and self.word is not None
class ListIterator:
def __init__(self, words):
self.words = words
self.i = 0
def next(self):
if not self.has_next():
return
res = self.words[self.i]
self.i += 1
return res
def has_next(self):
if self.i < len(self.words):
return True
return False