Created
March 15, 2016 16:52
-
-
Save markjenkins/7d77d3a135d7b227fc24 to your computer and use it in GitHub Desktop.
iterative, functional definition of the fibonacci sequence using reduce()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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