Python Program to Print Tribonacci Series
0, 1, 1 and then printing each next number as the sum of the previous three using a loop, for example: trib = [0, 1, 1]; for i in range(3, n): trib.append(trib[i-1] + trib[i-2] + trib[i-3]).Examples
How to Think About It
Algorithm
Code
def tribonacci(n): trib = [0, 1, 1] if n <= 3: return trib[:n] for i in range(3, n): trib.append(trib[i-1] + trib[i-2] + trib[i-3]) return trib n = int(input("Enter the number of terms: ")) result = tribonacci(n) print(' '.join(map(str, result)))
Dry Run
Let's trace the tribonacci series for n=5 through the code
Initialize list
trib = [0, 1, 1]
Check if n <= 3
n=5, so continue to loop
Loop iteration i=3
trib[2] + trib[1] + trib[0] = 1 + 1 + 0 = 2; trib = [0, 1, 1, 2]
Loop iteration i=4
trib[3] + trib[2] + trib[1] = 2 + 1 + 1 = 4; trib = [0, 1, 1, 2, 4]
End loop and return
Return [0, 1, 1, 2, 4]
| i | tribonacci list |
|---|---|
| Start | [0, 1, 1] |
| 3 | [0, 1, 1, 2] |
| 4 | [0, 1, 1, 2, 4] |
Why This Works
Step 1: Start with base numbers
The tribonacci series begins with fixed numbers 0, 1, 1 which are the first three terms.
Step 2: Calculate next terms
Each new term is the sum of the previous three terms, so we add trib[i-1] + trib[i-2] + trib[i-3].
Step 3: Use a loop to generate terms
A loop runs from the 4th term to the nth term, appending each new calculated term to the list.
Step 4: Print the series
Finally, the program prints all terms up to the requested count.
Alternative Approaches
def tribonacci_recursive(n): if n == 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] elif n == 3: return [0, 1, 1] else: seq = tribonacci_recursive(n-1) seq.append(seq[-1] + seq[-2] + seq[-3]) return seq n = int(input("Enter the number of terms: ")) result = tribonacci_recursive(n) print(' '.join(map(str, result)))
def tribonacci_vars(n): a, b, c = 0, 1, 1 result = [] for _ in range(n): result.append(a) a, b, c = b, c, a + b + c return result n = int(input("Enter the number of terms: ")) print(' '.join(map(str, tribonacci_vars(n))))
Complexity: O(n) time, O(n) space
Time Complexity
The program runs a single loop from 3 to n, so it takes linear time O(n).
Space Complexity
It stores all n terms in a list, so space complexity is O(n).
Which Approach is Fastest?
The iterative list approach is fastest and simplest; recursion is slower and uses more call stack memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative list | O(n) | O(n) | General use, easy to understand |
| Recursive | O(n) | O(n) call stack | Small n, educational purposes |
| Three variables | O(n) | O(n) | Memory efficient during calculation |