-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path139_Google_Create_Peekable_Iterator.py
executable file
·55 lines (40 loc) · 1.21 KB
/
139_Google_Create_Peekable_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
"""
Given an iterator with methods next() and hasNext(), create a wrapper iterator, PeekableInterface,
which also implements peek(). peek shows the next element that would be returned on next().
Here is the interface:
class PeekableInterface(object):
def __init__(self, iterator):
pass
def peek(self):
pass
def next(self):
pass
def hasNext(self):
pass
"""
class PeekableInterface(object):
def __init__(self, iterator):
self.iterator = iterator
self._next = next(iterator)
def peek(self):
return self._next
def next(self):
result = self._next
try:
self._next = next(self.iterator)
except StopIteration:
self._next = None
return result
def hasNext(self):
return self._next is not None
if __name__ == '__main__':
lst = [1, 2, 3, 4, 5]
peekable_lst = PeekableInterface(iter(lst))
assert peekable_lst.peek() == 1
assert peekable_lst.hasNext()
assert peekable_lst.next() == 1
assert peekable_lst.next() == 2
assert peekable_lst.next() == 3
assert peekable_lst.next() == 4
assert peekable_lst.next() == 5
assert not peekable_lst.hasNext()