Question: PYTHON: 1. Write a function collatz that takes one argument, a positive integer n. The function then generates and returns the Collatz sequence starting at

PYTHON:

1. Write a function collatz that takes one argument, a positive integer n. The function then generates and returns the Collatz sequence starting at n (and ending at 1). The Collatz sequence is a sequence obtained by repeatedly applying the following rule to the previous number in the sequence:

a. If a number is even, then the next number is that number divided by 2. Eg. 10 -> 5

b. If a number is odd, then the next number is 3 times the number plus 1. Eg 5 -> 16

Your function should stop when the sequence gets to 1. Note that it is an open question whether the Collatz sequence for every positive integer always ends at 1. Hint: you need to use a while loop. Hints: 1) do some on paper first!, 2) first write a while loop that prints the sequence, then 3) accumulate. Sample usage:

>>> collatz(10)

[10, 5, 16, 8, 4, 2, 1]

>>> collatz(22)

[22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!