-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathiterators_and_generators.py
More file actions
91 lines (72 loc) · 1.74 KB
/
iterators_and_generators.py
File metadata and controls
91 lines (72 loc) · 1.74 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
# return n fibonacci numbers
def fib1():
x = 0
y = 1
while True:
x, y = y, x+y
yield x
call = fib1()
l = []
for _ in range(5):
l.append(call.next())
print "Way 1:", l
def fib2(n):
x = 0
y = 1
for _ in range(n):
x, y = y, x+y
yield x
print "Way 2:", list(fib2(5))
class rev_iter():
'''
Writing your own iterable
__iter__ actually returns the iterable
'''
def __init__(self, n):
self.i = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.i < self.n:
n = self.n
self.n -= 1
return n
else:
raise StopIteration
ca = rev_iter(5)
print "Own iterable:", ca.next(), ca.next(), ca.next(), ca.next(), ca.next()
# Make this easier using generator
def rev_iter_using_generator(n):
for _ in range(n):
yield n
n -= 1
ca = rev_iter_using_generator(5)
print "Above using generator:", ca.next(), ca.next(), ca.next(), ca.next(), ca.next()
# generator expression like list comprehension
print "List comprehension: ", [x*x for x in range(1, 5)]
print "Generator: ", (x*x for x in range(1, 5))
print "List using generator", list((x*x for x in range(1, 5)))
# python factorial generator
def factorial(n):
fact = 1
some_count = 1
for _ in xrange(n):
yield fact
some_count += 1
fact *= some_count
n = 5
print("First %d factorials are: %s" %(n, list(factorial(n))))
print "*"*80
# use of send in generators
def fibonacci():
x, y, z = 0, 1, 0
while z < 4:
x, y = y, x+y
z = yield x
print x, z
ob = fibonacci()
for i in xrange(100):
print "Yielded value: ", ob.next()
if i == 5:
ob.send(i)