Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Tribonacci Series

Print a Tribonacci sequence using three previous terms in Python. Students handle short requested counts and update a three-value window after each new sum.

IntermediatePhase 6 - Category 4: Mathematical CombinationsExample 8 of 10
tribonacci-series.py
1# Take n
2n = int(input("Enter number of terms: "))
3
4# Generate Tribonacci
5if n <= 0:
6 print("Invalid input")
7elif n == 1:
8 print("0")
9elif n == 2:
10 print("0 1")
11elif n == 3:
12 print("0 1 1")
13else:
14 a, b, c = 0, 1, 1
15 print(a, b, c, end=" ")
16 for i in range(3, n):
17 d = a + b + c
18 print(d, end=" ")
19 a, b, c = b, c, d
20 print()

Output

Enter number of terms: 8
0 1 1 2 4 7 13 24

In this one

  • Maintain three previous terms
  • Handle short requests
  • Shift state simultaneously

How it works

  1. 1

    Handle counts up to three directly.

  2. 2

    Compute d as a + b + c.

  3. 3

    Print d and shift a, b, c to b, c, d.

Edge cases

What if n <= 0?

What if n <= 0?

Invalid input is printed.

What are this version's first three terms?

What are this version's first three terms?

Zero, one, one.

What's going on

This version starts 0, 1, 1. Each later term is the sum of the previous three, not the previous two.

The initial branches handle counts through three before the general loop begins. After d is computed, simultaneous assignment shifts a, b, c to b, c, d. For five terms, the sequence is 0 1 1 2 4. No list stores the full history.

What if n <= 0? Invalid input is printed.

What are this version's first three terms? Zero, one, one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

How many prior values form the next term?

Pick an answer to check it.

Question 2

What if n <= 0?

Pick an answer to check it.

Questions people ask

What if n <= 0?

Invalid input is printed.

What are this version's first three terms?

Zero, one, one.

How many prior values form the next term?

Three.