Question
The following code creates a dictionary of collatz sequences from 1 to 24 and then prints them out in order of their length. (python) def
The following code creates a dictionary of collatz sequences from 1 to 24 and then prints them out in order of their length. (python)
def collatz(n): """ Generate the collatz sequence starting from n. n must be >= 1. """ if n < 1: return Exception('Arg must be >= 1') if n == 1: return [1] next = 3*n+1 if n % 2 == 1 else n//2 return [n] + collatz(next)
# Create a dictionary with key n and value collatz(n) collatzes =
# Print out the sequences in order of their lengths. for (n, seq) in sorted(collatzes.items(), key=
The output should look like this,
1. [1] (length: 1) 2. [2, 1] (length: 2) 4. [4, 2, 1] (length: 3) 8. [8, 4, 2, 1] (length: 4) 16. [16, 8, 4, 2, 1] (length: 5) 5. [5, 16, 8, 4, 2, 1] (length: 6) 10. [10, 5, 16, 8, 4, 2, 1] (length: 7) 3. [3, 10, 5, 16, 8, 4, 2, 1] (length: 8) 20. [20, 10, 5, 16, 8, 4, 2, 1] (length: 8) 21. [21, 64, 32, 16, 8, 4, 2, 1] (length: 8) 6. [6, 3, 10, 5, 16, 8, 4, 2, 1] (length: 9) 12. [12, 6, 3, 10, 5, 16, 8, 4, 2, 1] (length: 10) 13. [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 10) 24. [24, 12, 6, 3, 10, 5, 16, 8, 4, 2, 1] (length: 11) 17. [17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 13) 11. [11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 15) 22. [22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 16) 23. [23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 16) 7. [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 17) 14. [14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 18) 15. [15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 18) 9. [9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 20) 18. [18, 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 21) 19. [19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1] (length: 21)
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