 # Untitled

May 14th, 2022
726
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. def gen1():
2.     for item in range(1, 10, 2):
3.         yield item
4.
5.
6. def gen2():
7.     for item in range(2, 20, 2):
8.         yield item
9.
10.
11. def gen3():
12.     for item in range(40, 50, 2):
13.         yield item
14.
15.
16. def merge_generators(gen1, gen2):
17.     """Live coding."""
18.     gen1_run = True
19.     gen2_run = True
20.     stop1 = False
21.     stop2 = False
22.     while True:
23.         try:
24.             if gen1_run:
25.                 value1 = next(gen1)
26.         except StopIteration:
27.             stop1 = True
28.         try:
29.             if gen2_run:
30.                 value2 = next(gen2)
31.         except StopIteration:
32.             stop2 = True
33.         gen1_run = True
34.         gen2_run = True
35.         if stop1 and stop2:
36.             break
37.         elif stop1:
38.             yield value2
39.         elif stop2:
40.             yield value1
41.         else:
42.             if value1 < value2:
43.                 yield value1
44.                 gen2_run = False
45.             else:
46.                 yield value2
47.                 gen1_run = False
48.
49.
50. def merge_2(*generators):
51.     """Not live coding."""
52.     # Generator, Should I run?, Current value
53.     matrix = [
54.         [gen, True, None] for gen in generators
55.     ]
56.     while matrix:
57.         for i, row in enumerate(matrix):
58.             if row is True:
59.                 try:
60.                     row = next(row)
61.                     row = False
62.                 except StopIteration:
63.                     matrix.pop(i)
64.         if matrix:
65.             lowest = min(matrix, key=lambda row: row)
66.             yield lowest
67.             lowest = True
68.
69.
70. def merge_3(*generators):
71.     """Shorter way."""
72.     # Generator, Should I run?, Current value
73.     matrix = [
74.         [gen, next(gen)] for gen in generators
75.     ]
76.     while matrix:
77.         lowest = min(matrix, key=lambda row: row)
78.         yield lowest
79.         try:
80.             lowest = next(lowest)
81.         except StopIteration:
82.             matrix = list(filter(lambda e: e != lowest, matrix))
83.
84.
85.
86. merge_gener = merge_3(gen1(), gen2(), gen3())
87.
88. print([i for i in merge_gener])
89.