-
Notifications
You must be signed in to change notification settings - Fork 0
/
139.py
85 lines (63 loc) · 1.84 KB
/
139.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
"""
Problem:
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
"""
from typing import Any, Iterable
class PeekableInterface(object):
def __init__(self, iterator: Iterable[Any]) -> None:
self.iterator = iterator
try:
self.next_val = next(self.iterator)
self.has_next = True
except StopIteration:
self.next_val = None
self.has_next = False
def peek(self) -> Any:
return self.next_val
def next(self) -> Any:
if self.has_next:
curr_elem = self.next_val
try:
self.next_val = next(self.iterator)
except StopIteration:
self.next_val = None
self.has_next = False
return curr_elem
return None
def hasNext(self) -> bool:
return self.has_next
if __name__ == "__main__":
sample_list = [1, 2, 3, 4, 5]
iterator = iter(sample_list)
peekable = PeekableInterface(iterator)
print(peekable.peek())
print(peekable.hasNext())
print(peekable.next())
print(peekable.next())
print(peekable.next())
print(peekable.peek())
print(peekable.hasNext())
print(peekable.next())
print(peekable.hasNext())
print(peekable.peek())
print(peekable.next())
print(peekable.hasNext())
print(peekable.peek())
print()
sample_list = []
iterator = iter(sample_list)
peekable = PeekableInterface(iterator)
print(peekable.peek())
print(peekable.hasNext())