-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem0002.py
64 lines (53 loc) · 1.63 KB
/
Problem0002.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
Enonce = """
Even Fibonacci numbers
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
# Iterator style
class Fibonacci:
def __init__(self, size=None, highest_value=None):
self.previous = [0, 1]
self.index = size
self.highest_value = highest_value
def __iter__(self):
return self
def __next__(self):
if self.index is not None:
if self.index == 0 :
raise StopIteration
self.index = self.index - 1
value = self.previous.pop(0) + self.previous[0]
self.previous.append(value)
if self.highest_value is not None:
if self.highest_value < value :
raise StopIteration
return value
# Iterable style (large memory)
def fibonacci(size):
if size == 1:
return [1]
elif size == 2:
return [1, 2]
else:
fibo = fibonacci(size-1)
fibo.append(fibo[-2]+fibo[-1])
return fibo
def main():
print(40*"=")
print(Enonce)
print(40*"-")
Solution = 0
highest = 4_000_000
print(f"Even Fibonacci values lower than {highest} :") # f"abc{toto}" == "abc{}".format(toto)
for v in Fibonacci(highest_value=highest):
if v%2 == 0:
print(v)
Solution += v
print(40*"-")
print("Solution = {}".format(Solution))
print(40*"=")
if __name__ == "__main__":
# execute only if run as a script
main()