Tuesday 16 June 2015

All the Classics

The third warm-up test is to create the first 100 members of the Fibonacci series.

OK, so let's consider the series two elements at a time as a and b: we can initialise neatly so:

>>> a, b = 0, 1

And accumulate the series in a list called fibo which we initialise empty:

>>> fibo = []

Then loop 100 times appending each element to our list and then moving on to the next with another neat parallel assignment:

>>> for ix in range(0, 100):
...     fibo.append(a)
...     a, b = b, a+b
...

So what do we get?

>>> print fibo
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4
181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 83
2040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169,
 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 18
36311903, 2971215073L, 4807526976L, 7778742049L, 12586269025L, 20365011074L, 329
51280099L, 53316291173L, 86267571272L, 139583862445L, 225851433717L, 36543529616
2L, 591286729879L, 956722026041L, 1548008755920L, 2504730781961L, 4052739537881L
, 6557470319842L, 10610209857723L, 17167680177565L, 27777890035288L, 44945570212
853L, 72723460248141L, 117669030460994L, 190392490709135L, 308061521170129L, 498
454011879264L, 806515533049393L, 1304969544928657L, 2111485077978050L, 341645462
2906707L, 5527939700884757L, 8944394323791464L, 14472334024676221L, 234167283484
67685L, 37889062373143906L, 61305790721611591L, 99194853094755497L, 160500643816
367088L, 259695496911122585L, 420196140727489673L, 679891637638612258L, 11000877
78366101931L, 1779979416004714189L, 2880067194370816120L, 4660046610375530309L,
7540113804746346429L, 12200160415121876738L, 19740274219868223167L, 319404346349
90099905L, 51680708854858323072L, 83621143489848422977L, 135301852344706746049L,
 218922995834555169026L]

Did we get them all?

>>> print len(fibo)
100

Ah yes.

No comments:

Post a Comment