-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunit4_ex4.3.4.py
62 lines (49 loc) · 1.46 KB
/
unit4_ex4.3.4.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
# exercise 4.3.4 from unit 4
'''
Write a generator function called get_fibo defined as follows:
def get_fibo():
The function returns a generator that produces members of the Fibonacci series.
In mathematics, the Fibonacci series is a series whose first two terms are 0 and 1 and each term after that is equal to the sum of the two numbers preceding it. Accordingly, the first members of the series are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...
An example of running the get_fibo generator function:
To view an accessible code snippet
fibo_gen = get_fibo()
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
Guidelines:
A generator function that returns a generator for generating numbers in the Fibonacci series.
'''
def get_fibo():
yield 0
yield 1
fibo_numbers = [0, 1]
while True:
length = len(fibo_numbers)
fibo_numbers.append(
fibo_numbers[length - 1] + fibo_numbers[length - 2])
yield fibo_numbers[len(fibo_numbers) - 1]
def get_fibo_better():
yield 0
yield 1
x = 0
y = 1
while True:
num = x + y
x = y
y = num
yield num
def main():
fibo_gen = get_fibo_better()
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
print(next(fibo_gen))
if __name__ == "__main__":
main()