How to generate the Collatz sequence in Python
The Collatz sequence is generated based on the following conditions:
- If the number is even, the function returns a value of
n//2. - If the number is odd, the function returns the value of
3*number+1.
We then continue this process until the function returns the value of 1.
Algorithm
Step-1:
Check wether or not the number is equal to one.
Step-2:
Check if a number is even or odd. If the number is even, print number//2; if the number is odd, print 3 * number+1.
For example:
Let the number be 11:
11 is odd, return 3*11+1=34
34 is even, return 34//2 = 17
17 is odd, return 17*3+1=52
52 is even, return 52//2=26
26 is even, return 26//2=13
13 is odd, return 13*3+1=40
40 is even,return 40//2=20
20 is even, return 20//2=10
10 is even, return 10//2=5
5 is odd, return 5*3+1=16
16 is even, return 16//2=8
8 is even, return 8//2=4
4 is even, return 4//2=2
2 is even,return 2//2=1
Code
def collatz(number):lst=[]lst.append(number)while(number!=1):if(number%2==0):number=number//2lst.append(number)else:number=number*3+1lst.append(number)print(lst)collatz(11)
-
An empty list is taken to store all sequence values.
-
Whileloop is taken to check if the condition is equal to one. -
If the number is not equal to one, the number is checked to see if it is
evenorodd. Based on this result, the subsequent operation is performed. -
All the values are appended to the list.
-
The list is the Collatz sequence of the given number.