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.
1# Take n2n = int(input("Enter number of terms: "))34# Generate Tribonacci5if 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, 115 print(a, b, c, end=" ")16 for i in range(3, n):17 d = a + b + c18 print(d, end=" ")19 a, b, c = b, c, d20 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
Handle counts up to three directly.
- 2
Compute d as a + b + c.
- 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.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum