Log in | Register



Fibonacci

This sample is saved as Fibonacci in the Samples subfolder of the Resolver One folder on your Start Menu. It is not so much an example of something done the right way in Resolver, as an example of the kind of interesting effect you can get once you start putting arbitrary Python objects into a spreadsheet grid. You could regard it as an example of a somewhat pathological but entirely new way of programming using a spreadsheet :-)

The aim of the sheet is to allow you to enter the starting values for a Fibonacci sequence and an index ''n'', and to get in return the ''n''th value of that sequence. Here's how it works.

In the pre-constants user code, the blue section, we define a simple Python generator:

def fibonacci(v1, v2):
    while True:
        yield v1
        v1, v2 = v2, v1 + v2

When called, it will return a generator that will give us the infinite Fibonacci series that starts with the two values that were passed in as parameters.

Back in the grid, we enter two values for a Fibonacci series into cells B1 and B2, then we call the generator - passing in B1 and B2 - in B3. The result is the generator, and as Resolver One cannot display an infinite series of numbers in a cell, it displays the Python string representation of the generator: something like <generator object at 0x0000000013E>.

This is not terribly useful on its own; in order to get value out of the generator, we need to extract values from it. In particular, the aim of this sheet is to get the ''n''th value from it, where ''n'' is the value in cell B4.

Ideally what we would like to do is ask the generator for its ''n''th value directly, using a formula like =B3[B4]. Unfortunately, generators do not support direct access to elements - in Python terms, they don't have a __getitem__ method. In order to get the ''n''th element, you need to ask for the first, the second, the third, and so on up to ''n''.

So what we have to do is work out some way of iterating through the generator up to its ''n''th element. The way to do that is to create a range up to the desired index (with 200 being the upper limit), and use the built-in zip function to combine that with the generator. zip will stop the iteration when either of the iterators is exhausted, so when we get to the end of the range, the generator will have been advanced to the desired index.

Cell B6, after all this messing around, is a bit of an anticlimax - we just index into the list in B5 with to get the B4th value from it. This gives us our result.

Back to Sample Spreadsheets.

Comments