famguy74 famguy74 - 1 month ago 9
Python Question

Counting number of steps till a number gets to 1

The goal of this function is to count the number of steps it takes a number to get to 1 after performing operations. The number you put into the function is divided by 2 if the number is even, and tripled and increased by 1 if the number is odd. These operations are performed on the number until it reaches one. For example, if you start out with the number 3 it would go through these steps: 3 >10 >5 >16 >8 >4 >2 >1 the function would need to return the number "8" because it took 8 steps for 3 to get to 1 after dividing even numbers and multiplying by 3 and adding 1 to odd numbers.

Here is my code so far. I understood how to have my function return the first step (Example: I could have 3 return 10 and 6 return 3) but I can't figure out how to have my function count the number of steps it took to reach 1.

def collatz_counts(n):
total = 0
while n > 1:
if n % 2 == 0:
n =(n // 2)
total += 1

elif n % 2 == 1:
n = (3 * n + 1)
total += 1
return total

Answer

You need to adjust the code to make it return after the while loop. Otherwise, it will return too early if it meet odd number.

Additionally, total += 1 is done in both case; you can move it out of if .. elif .. block.

def collatz_counts(n):
    total = 0
    while n > 1:
        if n % 2 == 0:
            n =(n // 2)
        elif n % 2 == 1:
            n = (3 * n + 1)
        total += 1  # <---
    return total  # <---

BTW, collatz_counts(3) will return 7. You need to adjust initial total value to 1 to get 8.

Comments