Fibonacci
This is not really an example of something done the right way in Resolver One. Rather, it demonstrates the kind of interesting effect you can get once you start putting arbitrary Python objects into a spreadsheet grid.
You will learn...
Before you begin
Do one of the following to open the sample workbook:
- In Windows, select Start, Resolver One, Samples, Fibonacci.
- Download a copy from the Resolver Exchange.
About the sample
The workbook allows you to enter the starting values for a Fibonacci sequence and an index 'n', and to get in return the nth value of that sequence.
How it works
Adding a Fibonacci generator to the grid
In the Pre-constants user code, the blue section, there is a simple Python generator:
def fibonacci(v1, v2): while True: yield v1 v1, v2 = v2, v1 + v2When called, this returns a generator. This gives us the infinite Fibonacci series that starts with the two values that were passed in as parameters.
Back in the grid, in B1 and B2 contains two starting values for a Fibonacci series.
Cell B3 calls the generator, passing in B1 and B2.
Resolver One cannot display an infinite series of numbers in a cell (!), so it displays the Python string representation of the generator, e.g. '<generator object at 0x0000000013E>'.
This is not terribly useful on its own. We need to extract values from it. That could be tricky...
Extracting values from the Fibonacci generator
The workbook is supposed to get the nth value of the Fibonacci sequence, where 'n' is the value in cell B4.
We can't ask the generator 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). So, in order to get the nth element, you need to ask for all the elements preceding it.
Now we must work out a way of iterating through the generator up to its nth element.
Cell B5 contains a formula that uses an interesting trick to iterating through the generator up to its B4th element:
It creates a range up to the desired index (with 200 being the upper limit)
It uses the built-in zip function to combine the range with the generator.
zip stops 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 indexes into B5 to get the nth value, where 'n' the contents of B4.
This gives us our result. (A bit of an anticlimax after all that messing around!)
Comments
If you have comments, questions or suggestions about any of the Resolver One documentation, please post them to the Documentation Suggestions Forum.
