Fibbonacci Recursive

Python

Public Domain

Demonstrate a recursive algorithm of the fibbonacci sequence

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/env python

"""This is a recursive algorithm example for the Fibonacci Sequence.  This was
made for fun, and it is released with no rights reserved."""

import sys

def _fi(max_term, num1=1, num2=1):
    """Fibonacci Sequence

    Private function for fi(...)."""

    if max_term == 1:
        num3 = num1 + num2
        return num3
    else:
        num3 = num1 + num2
        return _fi(max_term-1, num2, num3)

def fi(max_term):
    """Fibonacci Sequence

    max_term determines how many terms to iterate.  This function may break the
    recursion limit (see sys.{get,set}recursionlimit())  Terms start count at
    zero."""

    # The first two terms of the sequence are by definition 1
    if max_term < 0:
        raise ValueError, "Argument is less than zero"
    elif max_term == 0:
        return 0
    elif max_term == 1:
        return 1
    else:
        return _fi(max_term-1, 1, 1) #Drop the extra term (max_term-1)

if __name__ == "__main__":
    """Test the module.  Enter any number as the first argument to test an
    explicit number, else assign the default of 950."""

    try:
        max_term = int(sys.argv[1])
    except:
        max_term = 950

    print fi(max_term)