Luís Lopes
Luís Lopes

Reputation: 85

Collatz sequence (endless loop)

Firstly i know this is a very asked question. Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1.

def collatz(number):

  return [number //2 if number %2 == 0 else 3*number + 1]


number = int(input('Number - \n'))

while number != 1:

  result = collatz(number)
  print(result)

What i don't understand in my program is why it does the first operation and gets stuck in the first number. Like if i input 12 it returns 6 but gets stuck in the while loop by printing 6 forever. I want to understand what is wrong specifically in this program.

Upvotes: 0

Views: 248

Answers (2)

kske
kske

Reputation: 138

The problem is that you are not appending new elements to the list but rather replace the list with the current result. I have modified your code so that the list is filled with the elements from the sequence:

n = int(input("n="))
l = []
while n != 1:
  l.append(n);
  n = n // 2 if n % 2 == 0 else n * 3 + 1
print(l)

Upvotes: 1

Demosthenes
Demosthenes

Reputation: 1535

Your problem is that you are discarding result. You likely mean number = collatz(number)[0] (you use a list here for some reason).

Since you are not modifying number within your loop, the condition always evaluates to the same value and the input to collatz is always the same.

Upvotes: 1

Related Questions