Skip to content

Instantly share code, notes, and snippets.

@markjenkins
Created March 15, 2016 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markjenkins/7d77d3a135d7b227fc24 to your computer and use it in GitHub Desktop.
Save markjenkins/7d77d3a135d7b227fc24 to your computer and use it in GitHub Desktop.
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