|
| 1 | +def fibonacci(n): |
| 2 | + """return the nth value in the fibonacci sequence""" |
| 3 | + if n < 0: |
| 4 | + return None |
| 5 | + if n == 0: |
| 6 | + return 0 |
| 7 | + if n == 1: |
| 8 | + return 1 |
| 9 | + else: |
| 10 | + return fibonacci(n - 1) + fibonacci(n - 2) |
| 11 | + |
| 12 | +def lucas(n): |
| 13 | + """return the nth value in the lucas series""" |
| 14 | + if n < 0: |
| 15 | + return None |
| 16 | + if n == 0: |
| 17 | + return 2 |
| 18 | + if n == 1: |
| 19 | + return 1 |
| 20 | + else: |
| 21 | + return lucas(n - 2) + lucas(n - 1) |
| 22 | + |
| 23 | + |
| 24 | +def sum_series(n, value1 = 0, value2 = 1): |
| 25 | + """return the nth value of the given series |
| 26 | + where value1 and value2 are the first two values in the series""" |
| 27 | + if n < 0: |
| 28 | + return None |
| 29 | + if n == 0: |
| 30 | + return value1 |
| 31 | + if n == 1: |
| 32 | + return value2 |
| 33 | + else: |
| 34 | + return sum_series(n - 2, value1, value2) + sum_series(n - 1, value1, value2) |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +def lucas2(n): |
| 39 | + """return the nth number of the lucas numbers using the function sum_series""" |
| 40 | + return sum_series(n, 2, 1) |
| 41 | + |
| 42 | +def fibonacci2(n): |
| 43 | + """return the nth number of the fibonacci sequence using the function sum_series""" |
| 44 | + return sum_series(n, 0, 1) |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + # run some tests |
| 48 | + |
| 49 | + assert fibonacci(-1) is None |
| 50 | + assert fibonacci(-23) is None |
| 51 | + |
| 52 | + assert fibonacci(0) == 0 |
| 53 | + assert fibonacci(1) == 1 |
| 54 | + assert fibonacci(2) == 1 |
| 55 | + assert fibonacci(3) == 2 |
| 56 | + assert fibonacci(4) == 3 |
| 57 | + assert fibonacci(5) == 5 |
| 58 | + assert fibonacci(6) == 8 |
| 59 | + assert fibonacci(7) == 13 |
| 60 | + |
| 61 | + assert lucas(-1) is None |
| 62 | + assert lucas(-23) is None |
| 63 | + |
| 64 | + # do these with a loop: |
| 65 | + tests = [(0, 2), |
| 66 | + (1, 1), |
| 67 | + (2, 3), |
| 68 | + (3, 4), |
| 69 | + (4, 7), |
| 70 | + (5, 11), |
| 71 | + (6, 18), |
| 72 | + (7, 29), |
| 73 | + ] |
| 74 | + for input, output in tests: |
| 75 | + assert lucas(input) == output |
| 76 | + |
| 77 | + # test if sum_series matched Fibonacci |
| 78 | + for n in range(0, 10): |
| 79 | + assert sum_series(n) == fibonacci(n) |
| 80 | + |
| 81 | + # test if sum_series matched lucas |
| 82 | + for n in range(0, 10): |
| 83 | + assert sum_series(n, 2, 1) == lucas(n) |
| 84 | + |
| 85 | + # test if lucas1 matched lucas |
| 86 | + for n in range(0, 10): |
| 87 | + assert lucas2(n) == lucas(n) |
| 88 | + |
| 89 | + # test if fibonacci2 matched fibonacci |
| 90 | + for n in range(0, 10): |
| 91 | + assert fibonacci2(n) == fibonacci(n) |
| 92 | + |
| 93 | + print("tests passed") |
0 commit comments