-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab11_iterators.py
More file actions
83 lines (63 loc) · 1.62 KB
/
Copy pathlab11_iterators.py
File metadata and controls
83 lines (63 loc) · 1.62 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
from operator import add
class Naturals(object):
def __init__(self):
self.current = 0
def __next__(self):
result = self.current
self.current += 1
return result
def __iter__(self):
return self
class IterCombiner(object):
def __init__(self, iter1, iter2, combiner):
self.current1 = iter1.current
self.current2 = iter2.current
self.combiner = combiner
def __next__(self):
result = self.combiner(self.current1, self.current2)
self.current1 += 1
self.current2 += 1
return result
def __iter__(self):
return self
evens = IterCombiner(Naturals(), Naturals(), add)
ans = next(evens)
ans2 = next(evens)
class FibIter(object):
def __init__(self):
self.pred = 0
self.curr = 1
def __next__(self):
resp = self.pred
self.pred, self.curr = self.curr, self.pred + self.curr
return resp
def __iter__(self):
return self
flag = False
count = 0
while not flag:
fib = next(fibiter)
print(fib)
count += 1
if count == 5:
flag = True
def perfect_squares():
start = 0
first = 1
while True:
yield start
start = first**2
first += 1
"""
def perfect_squares():
start = 0
first = 1
while True:
if start == 0 or start == 1:
print(f'{start} is the square of {start}')
else:
print(f'{start} is the square of {first-1}')
yield start
start = first**2
first += 1
"""