Iterators and generators · 12 / 15 Exercise Medium

Collatz sequence

Objective

Create a Python program with a generator that produces the Collatz sequence, a generator whose length is not known beforehand.

Instructions

  • Define def collatz(n): while n is different from 1, yield n and change it to n // 2 if it is even or to 3 * n + 1 if it is odd. When it finishes, yield the final 1.
  • Read an integer n (at least 1) and store the sequence in a list with list(collatz(n)).
  • Show the sequence on one line, separated by spaces, and on the next one Steps: K, where K is the number of elements minus 1.
Input
6
Output
6 3 10 5 16 8 4 2 1
Steps: 8

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise