Python program for finding the Fibonacci series. More pythonic way

There is another thread to discuss the Fibo series in Python. This is necessary to configure the code for more pythonic. How to write a Fibonacci sequence in Python

I love this program that I wrote for Project Euler Q2. I recently code in Python and rejoice every time I do The Pythonic way! Can you suggest a better pythonic way to do this?

Project Euler Q2 . Find the sum of all even members in a Fibonacci sequence that do not exceed four million.

fib=[] def fibo(a=-1,b=1,upto=4000000): if a+b>=upto: return else: a,b=b,a+b fib.append(b) fibo(a,b) fibo() even=[i for i in fib if not i%2] print sum(even) 
+6
python
source share
9 answers

First I would make fibo () as a generator:

 def fibo(a=-1,b=1,upto=4000000): while a+b<upto: a,b = b,a+b yield b 

Then I would also choose for parity as a generator, and not for understanding the list.

 print sum(i for i in fibo() if not i%2) 
+12
source share

Using generators is a Python way to generate long sequences while preserving memory:

 def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b import itertools upto_4000000 = itertools.takewhile(lambda x: x <= 4000000, fibonacci()) print(sum(x for x in upto_4000000 if x % 2 == 0)) 
+16
source share

First, I would suggest summarizing the terms as they are computed, rather than storing them in an array and summing up the array after that, since you do not need to do anything with separate terms other than adding them. (This is just good computational sense in any language)

+4
source share

I would make the following changes:

  • Use iteration instead of recursion
  • Just keep the current amount instead of storing a list of all the Fibonacci numbers and then find the sum of the even backs

Other than that, it's reasonably Pythonic.

 def even_fib_sum(limit): a,b,sum = 0,1,0 while a <= limit: if a%2 == 0: sum += a a,b = b,a+b return sum print(even_fib_sum(4000000)) 
+2
source share

I would use a fibonacci generator, as in @constantin's answer, but generator expressions can be replaced with a simple for loop:

 def fibonacci(a=0, b=1): while True: yield a a, b = b, a + b sum_ = 0 for f in fibonacci(): if f > 4000000: break if f % 2 == 0: sum_ += f print sum_ 
+2
source share

Here's an alternative direct method. It relies on several properties:

  • Each Fibonacci number can be calculated directly as a gender (pow (phi, n) + 0.5) (See "Calculation by Rounding" at http://en.wikipedia.org/wiki/Fibonacci_number ). Conversely, the index of the largest Fibonacci number smaller than i is determined by gender (log (i * sqrt (5)) / log (phi))
  • The sum of the first Fibonacci numbers N is the N + 2nd Fibonacci number minus 1 (see The second certificate on the same wikipedia page).
  • Even Fibonacci numbers are every third number. (Look at the sequence mod 2, and the result is trivial)
  • The sum of the even Fibonacci numbers is half the sum of the odd Fibonacci numbers to the same point in the sequence.

From this you can see point 4:

 Sum of first 3N fibonacci numbers =(F(1) + F(2))+ F(3) +(F(4) + F(5))+ F(6) + ... +(F(3N-2) + F(3N-1))+ F(3N) = F(3) + F(3) + F(6) + F(6) + ... + F(3N) + F(3N) = 2( F(3) + F(6) + ... + F(3N) ) = 2 ( Sum of odd fibonacci numbers up to F(3N) ) 

So, we convert our maximum value of 4,000,000 to calculate the index of the highest Fibonacci number than it is.

 int n = floor(log(4000000*sqrt(5))/log(phi)); // ( = 33) 

33 is divided by 3, so this is an even Fibonacci number, if there was no need to adjust n.

 n = (n/3)*3; 

The sum of all Fibonacci numbers to this point, if given

 sum = floor( pow( phi, n+2 ) + 0.5 ) - 1; // ( = 9227464 ) 

The sum of all even numbers is half this:

 sum_even = sum/2; // ( = 4613732 ) 

The nice thing is that its O (1) (or O (log (N)), if you include the cost of the pow / log algorithm), and works at doubling .., so we can calculate the sum for very large values.

NOTE. I edited and moved this answer from a closed duplicate of this question. Fibonacci less than 4 million

+1
source share

In Python 3, if you give the generator a sum function, it will lazily evaluate it, so there is no need to reinvent the wheel.

Here is what @Constantin did and right.

Tested by comparing memory usage using generators:

sum(range(9999999))

compared to this:

sum(list(range(9999999)))

That with the generator does not cause a memory exception with higher numbers.

0
source share
 print ("Fibonacci Series\n") a = input ("Enter a nth Term: ") b = 0 x = 0 y = 1 print x,("\n"), y while b <=a-2: b = b+1 z = x + y print z x = y y = z 
0
source share
 def main(): a = 1 b = 2 num = 2 while b < 4000000: a, b = b, a+b num += b if b % 2 == 0 else 0 print num if __name__ == '__main__': main() 
0
source share

All Articles