Created
May 12, 2011 04:16
-
-
Save jeffgca/967915 to your computer and use it in GitHub Desktop.
Fibonacci sequence generator
This file contains hidden or 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
| from optparse import OptionParser | |
| parser = OptionParser() | |
| parser.add_option("-c", | |
| "--count", | |
| dest="count", | |
| help="how many?.", | |
| default=10 | |
| ) | |
| (options, args) = parser.parse_args() | |
| def gen_fib(limit): | |
| i,a,b = 0,0,1 | |
| while i <= limit: | |
| yield a | |
| i,a,b = i+1,b,a+b | |
| generator = gen_fib(options.count); | |
| for i in generator: | |
| print i |
This file contains hidden or 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
| # or you could do something like this | |
| # source: http://stackoverflow.com/questions/3953749/python-fibonacci-generator | |
| def genFib(): | |
| a,b = 0,1 | |
| while 1: | |
| yield a | |
| a,b = b,a+b | |
| # the generator is infinite, so you can just call next() | |
| f = genFib() | |
| x = [] | |
| for i in range(20): | |
| print f.next() | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lessons learned about Python during a technical interview