Skip to content

Instantly share code, notes, and snippets.

@DarkblooM-IO
Last active December 13, 2023 15:14
Show Gist options
  • Save DarkblooM-IO/9a18809147218ee310e5bfed5b93a02b to your computer and use it in GitHub Desktop.
Save DarkblooM-IO/9a18809147218ee310e5bfed5b93a02b to your computer and use it in GitHub Desktop.
Collatz Graph
#!/usr/bin/python3
import matplotlib.pyplot as plt # matplotlib>=3.8.2
from math import floor
def collatz(x: int) -> list[int]:
if x <= 0:
raise ValueError("x must be a positive integer")
output = []
while x > 1:
output.append(x)
x = floor(x/2 if x % 2 == 0 else (3 * x) + 1)
output.append(x)
return output
def main() -> None:
try:
val = int(input("Please enter a number: ").strip())
y = collatz(val)
x = [n for n in range(len(y))]
plt.plot(x, y)
plt.xlabel("Generation")
plt.ylabel("Value")
plt.title(f"Collatz Conjecture from {val}")
plt.show()
except ValueError:
return
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment