|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +series.py |
| 5 | +
|
| 6 | +solutions to the Fibonacci Series and Lucas numbers |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +def fibonacci(n): |
| 11 | + """ compute the nth Fibonacci number """ |
| 12 | + |
| 13 | + if n < 0: |
| 14 | + return None |
| 15 | + elif n == 0: |
| 16 | + return 0 |
| 17 | + if n == 1: |
| 18 | + return 1 |
| 19 | + else: |
| 20 | + return fibonacci(n - 1) + fibonacci(n - 2) |
| 21 | + |
| 22 | + |
| 23 | +def lucas(n): |
| 24 | + """ compute the nth Lucas number """ |
| 25 | + |
| 26 | + if n < 0: |
| 27 | + return None |
| 28 | + if n == 0: |
| 29 | + return 2 |
| 30 | + elif n == 1: |
| 31 | + return 1 |
| 32 | + else: |
| 33 | + return lucas(n - 1) + lucas(n - 2) |
| 34 | + |
| 35 | + |
| 36 | +def sum_series(n, n0=0, n1=1): |
| 37 | + """ |
| 38 | + compute the nth value of a summation series. |
| 39 | +
|
| 40 | + :param n0=0: value of zeroth element in the series |
| 41 | + :param n1=1: value of first element in the series |
| 42 | +
|
| 43 | + if n0 == 0 and n1 == 1, the result is the Fibbonacci series |
| 44 | +
|
| 45 | + if n0 == 2 and n1 == 1, the result is the Lucas series |
| 46 | + """ |
| 47 | + if n < 0: |
| 48 | + return None |
| 49 | + if n == 0: |
| 50 | + return n0 |
| 51 | + elif n == 1: |
| 52 | + return n1 |
| 53 | + else: |
| 54 | + return sum_series(n - 1, n0, n1) + sum_series(n - 2, n0, n1) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + # run some tests |
| 59 | + |
| 60 | + assert fibonacci(-1) is None |
| 61 | + assert fibonacci(-23) is None |
| 62 | + |
| 63 | + assert fibonacci(0) == 0 |
| 64 | + assert fibonacci(1) == 1 |
| 65 | + assert fibonacci(2) == 1 |
| 66 | + assert fibonacci(3) == 2 |
| 67 | + assert fibonacci(4) == 3 |
| 68 | + assert fibonacci(5) == 5 |
| 69 | + assert fibonacci(6) == 8 |
| 70 | + assert fibonacci(7) == 13 |
| 71 | + |
| 72 | + assert lucas(-1) is None |
| 73 | + assert lucas(-23) is None |
| 74 | + |
| 75 | + # do these with a loop: |
| 76 | + tests = [(0, 2), |
| 77 | + (1, 1), |
| 78 | + (2, 3), |
| 79 | + (3, 4), |
| 80 | + (4, 7), |
| 81 | + (5,11), |
| 82 | + (6,18), |
| 83 | + (7, 29), |
| 84 | + ] |
| 85 | + for input, output in tests: |
| 86 | + assert lucas(input) == output |
| 87 | + |
| 88 | + # test if sum_series matched Fibonacci |
| 89 | + for n in range(0, 10): |
| 90 | + assert sum_series(n) == fibonacci(n) |
| 91 | + |
| 92 | + # test if sum_series matched lucas |
| 93 | + for n in range(0, 10): |
| 94 | + assert sum_series(n, 2, 1) == lucas(n) |
| 95 | + |
| 96 | + print "tests passed" |
0 commit comments