Whilst trying to create a piece of code in order to prove the Collatz Conjecture, I tried to, in a single line, format all of the results (as can be seen in the last line of the script). Even though the output looks as desired, the last line in particular is over complex and long. I was wondering if someone could write the last couple lines together and better. Thanks!
PD: The last line of the script prints each value of the history = [] list and then adds an index to it. The output of 10, in turn, looks like this:
$python collatz.py
In: 10
0 | 10
1 | 5
2 | 16
3 | 8
4 | 4
5 | 2
6 | 1
Done!
Here's my code: (The code has now been edited based on the answers :))
#!/usr/bin/env python3
import time
def formulate(number):
history = []
counter = 0
while True:
history.append(number)
if number == 1:
break
if number % 2 == 0:
number = number // 2
else:
number = number * 3 + 1
counter += 1
return counter, history
counter, history = formulate(int(input("In: ")))
for idx, x in enumerate(history):
print("{} | {}".format(idx, x))
print('Done!')