Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

DB2 11 The Database For Big Data And Analytics

Authors: Cristian Molaro, Surekha Parekh, Terry Purcell, Julian Stuhler

1st Edition

1583473858, 978-1583473856

More Books

Students also viewed these Databases questions

Question

How are you going to arrange the furniture?

Answered: 1 week ago