Skip to content
This repository was archived by the owner on Apr 24, 2025. It is now read-only.

Commit f0b91ea

Browse files
committed
Added Collatz Conjecture code in repo
1 parent eacc708 commit f0b91ea

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Collatz Conjecture Iterator
2+
3+
This code snippet is a simple implementation of an iterator that generates the Collatz sequence for a given positive integer greater than 1. The Collatz sequence is a process where each number transforms based on the following rules:
4+
5+
- If the number is even, divide it by 2.
6+
- If the number is odd, multiply it by 3 and add 1.
7+
- Continue this process until you reach 1.
8+
9+
### Overview
10+
11+
The provided code defines a Collatz class that initializes with a positive integer n and implements the iterator pattern to generate the Collatz sequence. The `__next__()` method computes the next number in the sequence according to the rules above. It raises a StopIteration exception when the sequence reaches 1.
12+
#### Usage
13+
14+
1. When executed, the script prompts the user for a positive integer.
15+
2. The script then iterates through the Collatz sequence, printing each number in the sequence.
16+
3. The sequence ends when the iterator reaches 1, triggering the StopIteration exception.
17+
4. If an invalid input is entered (like a non-integer), a ValueError is raised, prompting the user with an error message.
18+
19+
#### How to Run
20+
21+
- Run the script in your Python environment.
22+
- In terminal write this command
23+
> python collatz.py
24+
25+
26+
#### Error Handling
27+
28+
- If the input is not a valid integer, a ValueError exception is raised, prompting the user to enter a valid integer.
29+
- If the iterator reaches 1, a StopIteration exception is raised, indicating the end of the sequence.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Collatz:
2+
def __init__(self, n):
3+
self.n = n
4+
5+
def __iter__(self):
6+
return self
7+
8+
def __next__(self):
9+
if self.n == 1:
10+
raise StopIteration
11+
if self.n % 2 == 0:
12+
self.n = self.n // 2
13+
else:
14+
self.n = 3 * self.n + 1
15+
return self.n
16+
17+
18+
19+
if __name__ == '__main__':
20+
print("To generate a Collatz Sequence, please provide an integer positive number")
21+
try:
22+
input_number = int(input("Please enter a number: "))
23+
for i in Collatz(input_number):
24+
print(i, end=" ")
25+
except StopIteration:
26+
print("Collatz sequence ended!")
27+
except ValueError:
28+
print("Input Should be an Integer!")

0 commit comments

Comments
 (0)