-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerators.py
85 lines (63 loc) · 1.55 KB
/
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
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
def create_cubes(n):
"""
This is a traditional way of generating sequences, not super memory efficient as it'll generate all values once and store them in memory
:param n: n
:return:
"""
result = []
for x in range(n):
result.append(x**3)
return result
for x in create_cubes(10):
print(x)
def create_cubes_yield_approach(n):
"""
This is using a more memory efficient way of creating sequences: yield
:param n:
:return:
"""
for x in range(n):
yield x**3
for x in create_cubes_yield_approach(10):
print(x)
def gen_fibo_traditional_approach(n):
a = 1
b = 1
output = []
for i in range(n):
output.append(a)
a, b = b, a + b
return output
for x in gen_fibo_traditional_approach(10):
print(x)
def gen_fibo_yield_approach(n):
a = 1
b = 1
for i in range(n):
yield a
a, b = b, a+b
for x in gen_fibo_yield_approach(10):
print(x)
def simple_gen():
for x in range(3):
yield x
for number in simple_gen():
print(number)
g = simple_gen() # this creates a generator object and very memory efficient,
# it won't hold anything extra in memory until next(g) is called
print(g)
print(next(g))
print(next(g))
print(next(g))
# print(next(g)) # this will throw StopIteration error
s = 'hello'
# for letter in s:
# print(letter)
# iter() is way to iterate over sequences
s_iter = iter(s)
print(next(s_iter))
print(next(s_iter))
print(next(s_iter))
print(s_iter.__next__())
print(s_iter.__next__())
# print(s_iter.__next__())