单一陈述斐波那契 [英] Single Statement Fibonacci
问题描述
可能重复:
斐波那契数,在Python 3中有一个内胆?a>
Possible Duplicate:
Fibonacci numbers, with an one-liner in Python 3?
这可能很容易,但是我对Python还是很陌生.我想出了这句话斐波那契.
It may be very easy thing, but I am very new to Python. I came up with this single statement Fibonacci.
[fibs.append(fibs[-2]+fibs[-1]) for i in xrange(1000)]
不过,并不是真正的单一陈述.在触发此语句之前,我需要初始化列表 fibs
,即 fibs = [0,1]
.
Not really single statement, though. I need to initialise the list, fibs
, before firing this statement i.e. fibs = [0, 1]
.
现在,我有2个问题,
-
我们如何摆脱此列表初始化语句
fibs = [0,1]
,以便使其真正成为单个语句?
How can we get rid of this list initialisation statement,
fibs = [0, 1]
, in order to make it really single statement?
原始语句打印 None
n 次;其中 n 是在 xrange()
中传递的数字.有什么办法可以完全避免这种情况?如果语句可以打印系列,则更好.然后,我们无需显式打印 fibs
.
Original statement prints None
n times; where n is the number passed in xrange()
. Is there any way to avoid that altogether? Or better if the statement can print the series, instead. Then we don't need to print fibs
explicitly.
[已编辑]
还是我们可以使用 list.append()
的替代方法,该方法返回附加到其上的 list
?
Or do we have any alternative to list.append()
which returns the list
it appends to?
推荐答案
这有效:
for n in range(1000):
print(0.4472135954999579392818347337462552470881236719223051448541*(pow(1.6180339887498948482045868343656381177203091798057628621354,n) - pow(-0.618033988749894848204586834365638117720309179805762862135,n)))
这是Binet公式的实现. http://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio
This is an implementation of Binet's Formula. http://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio
这篇关于单一陈述斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!