Skip to content

Instantly share code, notes, and snippets.

@bitsandbooks
Created May 15, 2012 21:31
Show Gist options
  • Save bitsandbooks/257857d4edd2f9350fc9 to your computer and use it in GitHub Desktop.
Save bitsandbooks/257857d4edd2f9350fc9 to your computer and use it in GitHub Desktop.
Using Python to Print Fibonacci Sequences
#!/usr/bin/python
"""
fib.py
A simple Fibonacci sequencer.
by Rob Dumas.
Public Domain (no copyright restrictions).
If someone using our program wants to get 13 numbers in the Fibonacci sequence
(or 10 or 100 or any other number), they have to edit our program by hand. Most
people don't want to do this, so Python has LIBRARIES (collections of tools)
that will allow you to pass arguments to the program at RUNTIME (when you run
the program).
"""
import sys # This library provides system-specific functions.
times = int( # Force the parameter to be an integer.
sys.argv[1] # The first argument after the program name.
)
# Define a function (fib) which takes one parameter (t).
def fib(t):
f = [ 0, 1 ] # Create a list with our seed values.
# len(f) equals 2 here and represents the start of our range.
for i in range(len(f),t):
fn = f[len(f)-1] + f[len(f)-2] # Hey, it's our Fibonacci formula!
f.append(fn)
print f # Print out the list.
fib(times) # Call function fib and pass the value of times as its parameter.
"""
Result:
$ ~: fib.py 12
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
$ ~: fib.py 15
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment