开发者

Single Statement Fibonacci [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Fibonacci numbers, with an one-liner in Python 3?

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)]

Not re开发者_JAVA百科ally single statement, though. I need to initialise the list, fibs, before firing this statement i.e. fibs = [0, 1].

Now, I have 2 questions,

  1. How can we get rid of this list initialisation statement, fibs = [0, 1], in order to make it really single statement?

  2. 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.

[Edited]

Or do we have any alternative to list.append() which returns the list it appends to?


This works:

for n in range(1000):
    print(0.4472135954999579392818347337462552470881236719223051448541*(pow(1.6180339887498948482045868343656381177203091798057628621354,n) - pow(-0.618033988749894848204586834365638117720309179805762862135,n)))

This is an implementation of Binet's Formula. http://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio


Well, this is not idiomatic at all. What you are doing here is using a list comprehension as a shortcut for a for loop. Though Python's comprehensions can have side effects, Python is not designed for this. I can't think of no way to get this to work and it is probably a good thing.

For your 2), consider that you are actually creating a list which items are return values of the call fibs.append(fibs[-2]+fibs[-1]) which is a side effect method and thus return None. See the doc for details.

Nice try but this is not what Python is for :)


def fib(n):
    return (n in (0,1) and [n] or [fib(n-1) + fib(n-2)])[0]

try this out

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜