Skip to content

Commit cdb8697

Browse files
committed
add zigzag iterator algorithm
1 parent 0b417f2 commit cdb8697

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

arrays/zigzag_iterator.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
zigzag iterator
3+
array1 = [1, 3, 5, 7, 9]
4+
array2 = [2, 4, 6, 8, 10]
5+
zigzag_iterator = ZigZag(array1, array2)
6+
while zigzag_iterator.has_next():
7+
print(zigzag_iterator.next(), end=" ")
8+
1 2 3 4 5 6 7 8 9 10
9+
"""
10+
11+
from copy import deepcopy
12+
from typing import List
13+
14+
15+
class ZigZag:
16+
def __init__(self, array1: list, array2: list):
17+
self.queue: List[list] = [
18+
deepcopy(array1), deepcopy(array2)
19+
]
20+
21+
def next(self):
22+
array = self.queue.pop(0)
23+
item = array.pop(0)
24+
if array:
25+
self.queue.append(array)
26+
return item
27+
28+
def has_next(self):
29+
return bool(self.queue)
30+
31+
32+
if __name__ == "__main__":
33+
array1 = [1, 3, 5, 7, 9]
34+
array2 = [2, 4, 6, 8, 10]
35+
zigzag_iterator = ZigZag(array1, array2)
36+
while zigzag_iterator.has_next():
37+
print(zigzag_iterator.next())

0 commit comments

Comments
 (0)