-1

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!')
  • 1
    How could a piece of code prove the Collatz conjecture? Do you intend to run it forever? – John Coleman Feb 09 '18 at 12:35
  • @JohnColeman well, if it still hasn't been proven, I am not going to. The script is just a proof of concept, i'll let the proving of the conjecture to the mathematicians ;) – aka witness Feb 09 '18 at 12:37
  • First, you need to make 2 changes in your code, 1. change `number/2` to `number//2`. 2. change `formulate(input("In: "))` to `formulate(int(input("In: ")))`. – Keyur Potdar Feb 09 '18 at 13:00
  • @KeyurPotdar im not sure about the difference between / and //, could you give me some help? – aka witness Feb 09 '18 at 13:14
  • https://stackoverflow.com/questions/183853/in-python-2-what-is-the-difference-between-and-when-used-for-division – Keyur Potdar Feb 09 '18 at 13:15
  • Makes sense to me, i'll be sure to change that :) @KeyurPotdar – aka witness Feb 09 '18 at 13:16

1 Answers1

1

I would just keep it simple and perform one print per output line:

counter, history = formulate(int(input("In: ")))
for idx, x in enumerate(history):
    print("{} | {}".format(idx, x))
print('Done!')
trincot
  • 317,000
  • 35
  • 244
  • 286