Skip to content

Commit 73038ad

Browse files
committed
Added programming task for 29-generators.md
1 parent e001094 commit 73038ad

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

29-generators.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ In this video, we learned how to create custom iterators in Python using generat
99
- [Why Generators?](#why-generators)
1010
- [Python Generators](#python-generators-1)
1111
- [Infinite Stream of Data with Generators](#infinite-stream-of-data-with-generators)
12-
12+
- [**Task**: Create Infinite Stream of Odd Numbers](#programming-task)
1313
---
1414

1515
## Why Generators?
@@ -173,3 +173,36 @@ print(next(seq))
173173
If we had used a for loop and a list to store this infinite series, we would have run out of memory.
174174

175175
However, with generators, we can keep accessing these items for as long as we want. It is because we are just dealing with one item at a time.
176+
177+
---
178+
179+
## Programming Task
180+
181+
Create a generator function to generate an infinite stream of odd numbers and print the first 10 elements.
182+
183+
```python
184+
def generate_odd():
185+
n = 1
186+
while True:
187+
yield n
188+
n += 2
189+
190+
odd_generator = generate_odd()
191+
192+
for num in range(10):
193+
print(next(odd_generator))
194+
```
195+
196+
**Output**
197+
```
198+
1
199+
3
200+
5
201+
7
202+
9
203+
11
204+
13
205+
15
206+
17
207+
19
208+
```

0 commit comments

Comments
 (0)