Single Statement Fibonacci [duplicate]

断了今生、忘了曾经 提交于 2019-12-12 14:04:18

问题


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 really 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?


回答1:


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




回答2:


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




回答3:


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

try this out



来源:https://stackoverflow.com/questions/6504319/single-statement-fibonacci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!