## Problem Description
Python Problem 1 is called the 3n+1 problem. This is an actual famous math/CS problem (search for Collatz conjecture). The objective here is to read in an input that consists of a pair of numbers. The first number is the starting point in a consecutive sequence of integers extending to the ending number. Each number is processed through the 3n+1 algorithm keeping track of the cycle time for each input to cycle to n=1.
Here is the calculation, if the number n is even, divide by 2. If the number is odd, multiply by 3 and add 1. The result of that is the new n, continue until you get to n=1. Keep track of how many cycles it takes to get to n=1 For example, an input might be 1 10 n=1 and done right away. Cycle time is 1 n=2, 2/2=1. Cycle time is 2 n=3 … n=10 The desired output is the input plus the longest cycle time. Input: 1 10 Output: 1 10 20 ## Solution
This problem is pretty straight forward. I created a class for the problem solution, file input and file output. There is a method that solves the actual 3n+1 calculation from input to n=1 and returns the number of cycles.
The main loop just keeps track of the longest cycle count and formats the output string. I'm still learning the best way to structure things, but I run with a main function like this: if __name__ == "__main__": execute_main()
They call this "dunder name, dunder main" and it's a way to either run your code from a terminal or import it like a script. (dunder is a way to say double underscore out loud - I guess I'm typing - oh well)
Here is an image of running the code like a script. Note that I added a print statement for this to work, the output is supposed to just go to a file
Look at that!
Other notes, I'm using VS Code on Linux for development. I also have been setting up a virtual environment for loading packages and keeping my install clean. I only used native Python for this, but it a good practice. See the full code on my Github
0 Comments
## Leave a Reply. |
## Archives
December 2022
## Categories |