-
Notifications
You must be signed in to change notification settings - Fork 0
/
generators.py
68 lines (44 loc) · 1.04 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
"""
Examples of generators
"""
nums_list = [1, 2, 3, 4, 5]
str_list = ['python', 'generators', 'examples']
def x10(nums: list):
for num in nums:
yield num * 10
ex_gen = x10(nums_list)
for ex in ex_gen:
print(ex)
# ---------------------
print('='*40)
# ---------------------
def awesome(words: list):
for word in words:
yield f"Awesome {word}!"
ex_gen = awesome(str_list)
for ex in ex_gen:
print(ex)
# ---------------------
print('='*40)
# ---------------------
ex_gen = awesome(str_list)
print(next(ex_gen))
print(ex_gen.__next__())
print(next(ex_gen))
# print(next(ex_gen_1))
# Traceback (most recent call last):
# File "computer-science-university\python\basics\generators.py", line 44, in <module>
# print(next(ex_gen_1))
# StopIteration
# ---------------------
print('='*40)
# ---------------------
def add_some(items: list):
for item in items:
addon = yield
yield addon + item
ex_gen = add_some(str_list)
addon = ''
for ex in ex_gen:
addon = ex_gen.send(addon)
print(addon)