easy +10 pts

Collatz Generator

Create a generator that yields the Collatz sequence from a starting number.

Write a generator function `collatz_sequence(n)` that takes a positive integer `n` and yields the Collatz sequence starting at `n` and ending at 1. The Collatz sequence is defined as: - If the current number is even, the next number is `current // 2`. - If the current number is odd, the next number is `3 * current + 1`. Yield each number in the sequence, including the starting number and 1. The sequence should be generated lazily, so the function must be a generator (use `yield`). You may assume `n` is a positive integer.

Constraints

Input `n` is a positive integer (1 <= n <= 10^9). The sequence will always eventually reach 1 (as conjectured). The generator should yield values until 1 is included.

Example

>>> list(collatz_sequence(6))
[6, 3, 10, 5, 16, 8, 4, 2, 1]
>>> list(collatz_sequence(1))
[1]
>>> list(collatz_sequence(3))
[3, 10, 5, 16, 8, 4, 2, 1]
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Start by yielding `n`, then update `n` according to the Collatz rules and continue until `n` becomes 1.
Use a `while` loop that yields the current value and then breaks after yielding 1.
Remember to handle `n == 1` at the very beginning so the sequence is just [1].
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.