How to Generate a Collatz Sequence in Python
Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.
Python code
17 linesdef collatz_sequence(n):
if n <= 0:
raise ValueError("n must be a positive integer")
sequence = [n]
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(n)
return sequence
if __name__ == "__main__":
start = 7
result = collatz_sequence(start)
print(f"Collatz sequence starting from {start}: {result}")
print(f"Length: {len(result)}")
Output
Collatz sequence starting from 7: [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Length: 17
How it works
The Collatz conjecture states that applying n // 2 for even numbers and 3 * n + 1 for odd numbers will always eventually reach 1 for any positive starting integer. The function accumulates each step in a list, starting with the initial value. An input validation guard ensures the function only accepts positive integers, raising a ValueError otherwise. The loop terminates when n becomes 1, so the sequence always includes the final 1.
Common mistakes
- Forgetting to handle invalid input like zero or negative numbers, causing an infinite loop.
- Using `/` instead of `//` for integer division, which produces floats and alters the sequence.
- Not initializing the sequence list with the starting value, so the output omits the first term.
Variations
- Use a generator expression to yield values one at a time instead of building a full list.
- Wrap the function in a recursive implementation to generate the sequence recursively.
Real-world use cases
- Implementing a teaching exercise in computer science courses to illustrate loops and conditionals.
- Verifying the Collatz conjecture for ranges of numbers in computational number theory research.
- Building a benchmark for performance testing of arithmetic-intensive loops in Python.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.