pythonpython-3.x

Collatz's hypothesis || want to reuse code instead of repeating


I am trying to learn python and came across this Collatz's hypothesis where I need to take any non-negative and non-zero integer number as input and if it's even, evaluate a condition otherwise, if it's odd, evaluate another condition if number ≠ 1, go back to even condition. I am checking same condition multiple times. Please guide me how to reuse the conditions without repeating them. Thank you in advance and my code is below. "was trying to reduce input intakes and minimize condition check for one"

c0 = int(input("Enter a non-negative and non-zero integer number: "))
steps = 0
if c0 < 0:
    c0 = input("Enter a non-negative and non-zero integer number: ")
else:
    while c0 != 1:
        while c0 % 2 == 0 and c0 != 0:
            c0 /= 2
            steps += 1
            print(int(c0))
            if c0 == 1:
                break
        else:
            c0 = 3*c0 + 1
            steps += 1
            print(int(c0))
    else:
        print("steps = ", steps)

Solution

  • Because you loop through it and regularly check for c0 being 1 and c0 not being 0, why not just use that as the while condition? Using it would make the break check unnecessary. Additionally, you don't need to use a while loop to check for even or odd numbers. Instead, you can use one while loop and conditionals inside.

    Also, you check for < 0 instead of <= 0 in your first conditional. Additionally since c0 can never equal 0, you don't need to check for it in the loop.

    c0 = int(input("Enter a non-negative and non-zero integer number: "))
    steps = 0
    if c0 <= 0: #Checks for negative or 0
        c0 = input("Enter a non-negative and non-zero integer number: ")
    else:
        while c0 != 1: #Checks if c0 is 1. If so, print the steps and terminate
            if c0 % 2 == 0: #If c0 is even
                c0 /= 2
                steps += 1
                print(int(c0))
            else: #If c0 is odd
                c0 = 3*c0 + 1
                steps += 1
                print(int(c0))
        else:
            print("steps = ", steps)