[Project Euler]2. Even Fibonacci numbers
[문제]
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.
[풀이]
def Fibo(n):
result = []
if n==1:
result = [1]
elif n==2:
result = [1,2]
else:
result = [1,2]
while n>=result[-1]+result[-2]:
result.append(result[-2]+result[-1])
return result
a_list = list(filter(lambda a: a%2==0, Fibo(4000000)))
a_sum = sum(a_list)
'''
우선 n이하까지의 피보나치 리스트를 생성해주는 함수를 만들었다.
시작 값이 1과 2이기 때문에 1과 2로 첫 값에 대한 처리를 해줬다.
([-2], [-1] 인덱스를 사용할 것이기 때문에 최소한 2개의 값이 있어야 함)
나머지 경우에 대해서는 [-2]+[-1]값을 result리스트에 넣어줬다.
(0이하의 값이 들어오면 원하지 않는 값이 나오지만 어쨋든..)
Fibo(n)의 return은 n 이하의 피보나치 리스트이고
a_list는 filter와 lambda를 사용해서 400만 이하의 피보나치 리스트 중 짝수만 걸러낸 리스트이다.
마지막으로 sum을 사용해서 a_list의 합계를 구했다.
'''