How can I store a result in a Matrix?
Steven Bethard
steven.bethard at gmail.com
Fri Nov 19 21:30:58 CET 2004
Ben Champion wrote:
> I am new to Python so please excuse me if this sounds simple! Before I
> explain what i want to do let me write some code in matlab which
> demonstrates what I would like to acheive, using the Fibonnachi series
> as an example:
[snip matlab code]
>
> This gives me the variable y with values
> 2 3 5 8 13 21 34 55 89 144
If you really want to be dealing with matrices, you should probably
dowload the numarray package:
http://www.stsci.edu/resources/software_hardware/numarray
If a list is sufficient, I would write this something like:
>>> def fib():
... a, b = 1, 1
... while True:
... yield a
... a, b = b, a + b
...
>>> import itertools as it
>>> list(it.islice(fib(), 2, 12))
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
The fib function is a generator that will yield, one at a time, each
value in the fibonacci sequence. Since you only wanted values 2 through
11 in your example, I use itertools.islice to select the appropriate
part of the generated sequence.
Note also that because Python has tuple unpacking, you can do multiple
simulaneous assignment, so there's no need to have that extra temp
variable 'z'.
Steve
More information about the Python-list
mailing list