
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Collatz sequence in Python
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
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
- Related Articles
- C++ program to implement Collatz Conjecture
- Connell sequence in Python
- Python Sequence Types
- Longest Consecutive Sequence in Python
- Python Text Sequence Types
- Python Binary Sequence Types
- Find maximum length Snake sequence in Python
- Program to find nth sequence after following the given string sequence rules in Python
- What is a sequence data type in Python?
- How to iterate by sequence index in Python?
- How to Merge Elements in a Python Sequence?
- Program to find number of ways we can select sequence from Ajob Sequence in Python
- Find element position in given monotonic sequence in Python
- Second most repeated word in a sequence in Python?
- Find bitonic point in given bitonic sequence in Python

Advertisements