Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Statement Fibonacci [duplicate]

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?

like image 885
Adeel Ansari Avatar asked Nov 29 '25 23:11

Adeel Ansari


2 Answers

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

like image 98
Zéychin Avatar answered Dec 02 '25 14:12

Zéychin


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

like image 44
Evpok Avatar answered Dec 02 '25 13:12

Evpok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!