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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started