Skip to content

Instantly share code, notes, and snippets.

@peterldowns
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save peterldowns/10ad5bf356e243326aef to your computer and use it in GitHub Desktop.

Select an option

Save peterldowns/10ad5bf356e243326aef to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# coding: utf-8
import click
import math
from functools import partial
from itertools import imap
from sys import stdout
def fib(n, as_float=False):
# Implementation of a closed form solution for the n-th Fibonacci number.
# Returns the value as an integer if `as_float` is falsy or else as a floating
# point representation of that integer.
#
# Derivation can be found here:
# http://www.austinrochford.com/posts/2013-11-01-generating-functions-and-fibonacci-numbers.html
sqrt5 = math.sqrt(5);
int_f = (lambda x: x) if as_float else int
return int_f(
(1.0 / sqrt5) * (
math.pow((1 + sqrt5) / 2, n) -
math.pow((1 - sqrt5) / 2, n)))
def fib_seq(n, **fib_kwargs):
# Return an iterator over the first n numbers in the Fibonacci sequence. Any
# additional keyword arguments will be passed to the function generating the
# n-th Fibonacci number, `fib`.
fib_kwargs = fib_kwargs or {}
assert not (n % 1) and n >= 0, "n must be an integer greater than 0"
return imap(partial(fib, **fib_kwargs), xrange(n))
@click.command()
@click.option('-n',
required=True,
type=click.INT,
help='Number of Fibonacci numbers to generate')
@click.option('as_json', '--json', is_flag=True)
@click.option('as_float', '--float/--int', is_flag=True, default=False)
def main(n, as_json, as_float):
# Print the first n Fibonacci numbers, with various formatting options.
seq = imap(str, fib_seq(n, as_float=as_float))
if as_json:
stdout.write('[%s]' % ','.join(seq))
else:
stdout.write(' '.join(seq))
stdout.write('\n')
stdout.flush()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment