I am relatively new in programming in Python and this is my fist post in Stack Overflow. Can someone tell me if this code is full proof for Collatz Sequence in Python. Thanks
def collatz(number):
while True:
if number % 2 == 0:
number = number // 2
else:
number = 3 * number + 1
print(number)
if number == 1:
break
while True:
try:
number = int(input("Enter a positive non-zero integer: "))
if number <= 0:
print("Please enter a positive non-zero integer.")
else:
collatz(number)
break
except ValueError:
print("Please enter a valid integer.")
To check I have tried with negative integer, 0 and 1 and string as an input.
The question is indeed what vague. The code can never be a mathematical proof of the presumption from Collatz. But if you mean if this code can be used to test if a certain number holds the presumption of Collatz. Than yes your code is correct to test this.This presumtion is a easy loop and you are doing that right.
In theory you could make it a bit compacter and faster (but note that the code is already fast enough). Other minor improvements are:
This uses uses a bitwise operator: & (for checking the even number), removes an if statement and uses bit-shifting operator: >> And with enormous numbers you probably don't want to print the numbers