HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Making this reduce() Fibonacci generator better

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisfibonaccibettergeneratorreducemaking

Problem

I've recently discovered how cool reduce() could be and I want to do this:

>>> a = [1, 1] + [0] * 11
>>> count = 1
>>> def fib(x,n):
...     global count
...     r = x + n
...     if count >>
>>> reduce(fib,a,1)
610
>>> a
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]


But this just looks so messy and almost defeats the purpose of the last line:

reduce(fib,a,1)


What would be a better way to use Python to make a Fibonacci number with reduce()?

Solution

A reduce (that's it, a fold) is not exactly the abstraction for the task (what input collection are you going to fold here?). Anyway, you can cheat a little bit and fold the indexes even if you don't really use them within the folding function. This works for Python 2.x:

def next_fib((x, y), n):
    return (y, x + y)

reduce(next_fib, xrange(5), (1, 1))[0]
#=> 8

Code Snippets

def next_fib((x, y), n):
    return (y, x + y)

reduce(next_fib, xrange(5), (1, 1))[0]
#=> 8

Context

StackExchange Code Review Q#20986, answer score: 4

Revisions (0)

No revisions yet.