Here is my code to generate values in the fibonnacci sequence below 10,000,000.
3 fibs = [1,1]
4 while((x = fibs[-1] + fibs[-2]) <= 10000000):
5
-
Basically:
fibs = [1]
x = 1
while(x <= 10000000):
fibs.append(x)
# It is not possible for "fibs" not to have
# at least two elements by now
x = fibs[-1] + fibs[-2]
(It was, in fact, one of the design goals of Python to avoid mixing expressions and assignments like C — that's why there's no x++
, x--
, which is also a semi-FAQ.)
讨论(0)
-
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct.
Please check
http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm
讨论(0)
-
from functools import partial
from itertools import imap, islice, takewhile
import operator
fibs = [1, 1]
for x in takewhile(partial(operator.ge, 10000000),
imap(operator.add, fibs, islice(fibs, 1, None))):
fibs.append(x)
Oh wait, you said "simplest"? Nevermind then.
讨论(0)
-
In Python, assignment is not an expression, and therefore has no value.
The simplest solution is to do the assignment in the first part of the loop:
fibs=[1,1]
while fibs[-1] <= 10000000:
fibs.append(fibs[-1] + fibs[-2])
讨论(0)
- 热议问题