Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
iterative, functional definition of the fibonacci sequence using reduce()
#!/usr/bin/evn python
# An iterative, functional definition of the fibonacci sequence using reduce()
# This is how I originally wrote this.
# map is going to be removed from the builtin namespace. So the newer
# version below doesn't use them.
#
# Advocates for removing lambda would consider this to be a good example
# of why it should be removed.
#
def fibo(n):
"""Find the nth fibonacci number
"""
return reduce( lambda (a, b), count: (b, a+b), xrange(n), (0, 1) )[0]
print map( fibo, xrange(20) )
def fibo_switch((a, b), count):
"""Take a tuple representing the current two numbers of interest in the
fibonacci sequence and produce a new tuple that advances the sequence.
We make the first number the current last, and the last number the
sum of the current first and last.
"""
return (b, a+b)
def fibo(n):
"""Find the nth fibonacci number
"""
return reduce( fibo_switch, xrange(n), (0, 1) )[0]
# Print a list of the first 20 fibonacci numbers
print [ fibo(n) for n in xrange(20) ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment