-
Notifications
You must be signed in to change notification settings - Fork 0
/
generators.py
53 lines (38 loc) · 1017 Bytes
/
generators.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
# essentially this is what a for loop is doing behind the scenes
def special_for_loop(iterable):
iterator = iter(iterable)
while True:
try:
print(iterator)
print(next(iterator))
except StopIteration:
break
# this mimics what a range does
class MyGen():
current = 0
def __init__(self, first, last):
self.first = first
self.last = last
def __iter__(self):
return self
def __next__(self):
if MyGen.current < self.last:
num = MyGen.current
MyGen.current += 1
return num
raise StopIteration
gen = MyGen(0, 100)
for i in gen:
print(i)
# special_for_loop([1, 2, 3, 4])
# def generator_function(num):
# for i in range(num):
# yield i
# g = generator_function(100)
# print(next(g))
# next(g)
# next(g)
# print(next(g))
# # since generators are iterables you can loop through them
# # for item in generator_function(10000):
# # print(item)