# Collatz sequence in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a positve integer n, we have to find the length of its Collatz sequence. As we know Collatz sequence is generated sequentially where n = n/2 when n is even otherwise n = 3n + 1. And this sequence ends when n = 1.

So, if the input is like n = 13, then the output will be 10 as [13, 40, 20, 10, 5, 16, 8, 4, 2, 1] these is the sequence.

To solve this, we will follow these steps −

• if num is same as 0, then
• return 0
• length := 1
• while num is not same as 1, do
• num :=(num / 2) when num mod 2 is 0 otherwise (3 * num + 1)
• length := length + 1
• return length

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, num):
if num == 0:
return 0
length = 1
while num != 1:
num = (num / 2) if num % 2 == 0 else (3 * num + 1)
length += 1
return length
ob = Solution()
print(ob.solve(13))

## Input

13

## Output

10