Created
July 28, 2011 16:29
-
-
Save jonschoning/1111878 to your computer and use it in GitHub Desktop.
Fibonacci numbers, with an one-liner in Python 3?
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
#Here's an implementation that doesn't use recursion, and only memoizes the last two values instead of the whole sequence history. | |
#nthfib() below is the direct solution to the original problem (as long as imports are allowed) | |
#It's less elegant than using the Reduce methods above, but, although slightly different that what was asked for, it gains the ability to to be used more efficiently as an infinite generator if one needs to output the sequence up to the nth number as well (re-writing slightly as fibgen() below). | |
# from itertools import imap, islice, repeat | |
# nthfib = lambda n: next(islice((lambda x=[0, 1]: imap((lambda x: (lambda setx=x.__setitem__, x0_temp=x[0]: (x[1], setx(0, x[1]), setx(1, x0_temp+x[1]))[0])()), repeat(x)))(), n-1, None)) | |
# >>> nthfib(1000) | |
# 43466557686937456435688527675040625802564660517371780402481729089536555417949051 | |
# 89040387984007925516929592259308032263477520968962323987332247116164299644090653 | |
# 3187938298969649928516003704476137795166849228875L | |
from itertools import imap, islice, repeat | |
fibgen = lambda:(lambda x=[0,1]: imap((lambda x: (lambda setx=x.__setitem__, x0_temp=x[0]: (x[1], setx(0, x[1]), setx(1, x0_temp+x[1]))[0])()), repeat(x)))() | |
list(islice(fibgen(),12)) | |
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment