Last active
October 7, 2024 08:09
-
-
Save menjaraz/1d98b766709dc33cfa797dc561a7b6fa to your computer and use it in GitHub Desktop.
Python Collatz Generator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generate_collatz(n): | |
""" | |
Generator function to generate the Collatz sequence. | |
Args: | |
n (int): The starting number for the sequence. | |
Yields: | |
int: The next number in the sequence. | |
""" | |
while n != 1: | |
yield n | |
if n % 2 == 0: | |
n = n // 2 | |
else: | |
n = 3 * n + 1 | |
yield 1 | |
def print_collatz_sequence(n): | |
""" | |
Prints the Collatz sequence starting from the given number. | |
Args: | |
n (int): The starting number for the sequence. | |
""" | |
print("\nCollatz sequence starting from", n, ":") | |
#for num in generate_collatz(n): | |
# print(num) | |
Collatz_list = list(generate_collatz(n)) | |
print(Collatz_list) | |
if __name__ == '__main__': | |
# Example usage: | |
print_collatz_sequence(67) | |
print_collatz_sequence(101) | |
print_collatz_sequence(19) | |
print_collatz_sequence(29) | |
print_collatz_sequence(11) | |
print_collatz_sequence(17) | |
print_collatz_sequence(13) | |
print_collatz_sequence(5) | |
print_collatz_sequence(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment