-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerators.py
More file actions
98 lines (67 loc) · 1.94 KB
/
generators.py
File metadata and controls
98 lines (67 loc) · 1.94 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
# Generators — memory-efficient iterables using the yield keyword.
#
# A normal function builds and returns a complete list.
# A generator function yields values one at a time, generating each on demand.
# This avoids storing the entire sequence in memory.
# --- Normal function returning a list ---
print('Normal function:')
def squares():
result = []
for x in range(10):
result.append(x ** 2)
return result
print(squares())
# --- Generator function using yield ---
print('\nGenerator function:')
def squares_gen():
for x in range(10):
yield x ** 2
print(squares_gen()) # <generator object> — not the list itself
for x in squares_gen():
print(x, end=' ')
print()
# --- Generator expression ---
# Like a list comprehension but with round brackets.
# (Round brackets are not used for tuple comprehensions — they produce generators.)
print('\nGenerator expression:')
squares_exp = (x ** 2 for x in range(10))
print(squares_exp) # <generator object>
for x in squares_exp:
print(x, end=' ')
print()
# --- Processing a large range ---
# A list of 1,000,000 items uses significant memory.
# A generator processes each value without storing the sequence.
print('\nLarge range (first 10):')
def large_range_gen():
for x in range(1_000_000):
yield x ** 2
for x in large_range_gen():
if x >= 100:
break
print(x, end=' ')
print()
# --- Infinite sequence ---
# Impossible with a list — a generator has no problem.
print('\nInfinite sequence (first 10):')
def infinite_sequence():
num = 0
while True:
yield num
num += 1
for i, x in enumerate(infinite_sequence()):
print(x, end=' ')
if i >= 9:
break
print()
# --- Infinite Fibonacci sequence ---
print('\nFibonacci (first 10):')
def fibonacci_gen():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci_gen()
for _ in range(10):
print(next(fib), end=' ')
print()