python don't have such feature of using while
in a comprehension (which is like a map combined with filter), but you can accomplished that using other tools like making a function that do what you desire or using your best friend the itertools module. For example
example 1, with itertools
>>> from itertools import takewhile
>>> def fib():
fk,fk1 = 0,1
while True:
yield fk
fk, fk1 = fk1, fk + fk1
>>> list(takewhile(lambda fn:fn<100,fib()))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>
example 2, with a function
>>> def fib_while(tope):
fk,fk1 = 0,1
while fk < tope:
yield fk
fk,fk1 = fk1, fk + fk1
>>> list(fib_while(100))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>>
oh, I forgot to mention, but your formula for getting the Fibonacci numbers, even if mathematical correct, is doom to fail to get the real value for a large enough n, because floating point arithmetic rounding errors
the point of divergence is very easy to found (using the above fib
)
>>> def fib_float(n):
return int(((1+(5**0.5))**n-(1-(5**0.5))**n)/(2**n*(5**0.5)))
>>> [n for n,f in zip(range(100),fib()) if f!=fib_float(n)] )
[72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>>
so for all n>=72 what you get are not Fibonacci numbers...
if you only care for all numbers in the sequence below 4,000,000 then that is not a problem of course as the limit is n=33