Sunday, July 15

Fibonacci and yield

Look at this problem 25 from euler project below:



Yes it is simple recursion:


But this one is like running forever. Considering the fact it needs the first number with 1000 digits, not surprising.

Then I start browsing and googling, met this one, using yield to generate fibonacci number; hell, when I saw the word "yield" I was like YEAH THATS IT:


When I run it I almost wet myself. So fast that makes you cant help but sing a song about it.

Basically, it returns a generator. Generator in python is lazy, it never actually calculates the next one until you force it by calling next. Old version every time it generates a new fib number, it goes to the very first and runs back one by one later. When number gets big the problem is like hell. Use generator however, you only do one addition every time, plus, in the while loop, you only return one number each time. Well I dont know you, but to a python rookie like me...


what happens to the old version? Still running.

No comments:

Post a Comment