View the step-by-step solution to:

Question

Problem 2: (3 points) Define a new function named collatz that takes one positive integer as a parameter and

returns a list of numbers, starting with the initial number. Then use a while loop to add to the list using the following process: - Let n be the value currently at the end of the list. - If n is even, add to the list the number: (n // 2) - If n is odd, add to the list the number: (3*n + 1) - If the number 1 is added to the list, the function should return the entire list. 2 This problem is known as the Collatz conjecture and for any value of n, the list will eventually get to a 1 (though this hasn't been formally proven) Here are some examples of output: >>> collatz(5) [5, 16, 8, 4, 2, 1] >>> collatz(6) [6, 3, 10, 5, 16, 8, 4, 2, 1]

Top Answer

View the full answer
Screenshot_1.jpg

1 def collatz (n) :
2
lists = while(n != 1) :
4
lists . append (n)
if (n%2 == 0) :|
n = int(n/2)
else:
8
n = int(3*n+1)
9
lists . append (n)
10
return lists
11
12
print (collatz(5) )
13
print...

Sign up to view the full answer

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question