- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements