RESOURCES:
Class slides: https://docs.google.com/presentation/d/1bqum5T0zURUajP4D2nLF0ZXGgpAACazOu-t56SYk0zk/edit?usp=sharing
Example code: https://replit.com/@ShravyaS/IntroToPython-11
HOMEWORK:
The tribonacci sequence is similar to the fibonacci sequence, but each term is the sum of the three terms before it. Write a recursive function to calculate the n-th tribonacci number, if the first three are 0, 0, 1.
ex. 0, 0, 1, 1, 2, 4, 7, …
(Code for the Fibonacci sequence is in slides.)
Write your answer as a comment, and we’ll post the solution by next class. See you then!
def tribonacci(n): if n == 1: return 0 elif n == 2: return 0 elif n == 3: return 1; else: next = tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3); return next print("Here is the tribonacci sequence up to n = 10") n = 1; while n <= 10: print(tribonacci(n)); n += 1;
print('How many numbers from the Tribonacci sequence do you want?') n = int(input()) print('') if n > 0: print('0') def Tribonacci(n): if n == 1: return 1 if n == 2: return 1 if n == 3: return 2 next = Tribonacci(n-1) + Tribonacci(n-2) + Tribonacci(n-3) return next for n in range(1,n): print(Tribonacci(n))
Solution:
def tribonacci(n): if n == 1: return 0 elif n == 2: return 0 elif n == 3: return 1 elif n > 3: x = tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3) return x print(tribonacci(int(input())))