Skip to content

Commit 5400fba

Browse files
committed
Add-Derderderr
1 parent 99b15b7 commit 5400fba

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import time
2+
import matplotlib.pyplot as plt
3+
4+
def collatz_sequence(n):
5+
"""Generate the Collatz sequence for n."""
6+
steps = [n]
7+
while n != 1:
8+
n = n // 2 if n % 2 == 0 else 3 * n + 1
9+
steps.append(n)
10+
return steps
11+
12+
13+
def visualize(sequence, title="Collatz Sequence"):
14+
plt.clf()
15+
plt.plot(sequence, marker='o')
16+
plt.title(title)
17+
plt.xlabel("Step")
18+
plt.ylabel("Value")
19+
plt.yscale("log") # makes visualization MUCH nicer
20+
plt.grid(True)
21+
plt.pause(0.01)
22+
23+
24+
def auto_mode(interval):
25+
print("\nAuto mode started.")
26+
print("Press SPACE in the plot window to stop.\n")
27+
28+
plt.ion()
29+
stop = False
30+
31+
def on_key(event):
32+
nonlocal stop
33+
if event.key == ' ':
34+
stop = True
35+
36+
fig = plt.figure()
37+
fig.canvas.mpl_connect("key_press_event", on_key)
38+
39+
n = 1
40+
while not stop:
41+
seq = collatz_sequence(n)
42+
visualize(seq, f"Collatz Sequence for n = {n}")
43+
n += 1
44+
time.sleep(interval)
45+
46+
plt.ioff()
47+
plt.show()
48+
print("Auto mode stopped.")
49+
50+
51+
# --- Main Program ---
52+
try:
53+
num = int(input("Enter a positive integer (or -1 for auto mode): "))
54+
55+
if num == -1:
56+
interval = float(input("Enter step interval time (seconds): "))
57+
auto_mode(interval)
58+
59+
elif num <= 0:
60+
print("Please enter a positive number greater than 0.")
61+
62+
else:
63+
seq = collatz_sequence(num)
64+
print("\nCollatz sequence:")
65+
for i, value in enumerate(seq, start=1):
66+
print(f"Step {i}: {value}")
67+
68+
plt.ion()
69+
visualize(seq, f"Collatz Sequence for n = {num}")
70+
plt.ioff()
71+
plt.show()
72+
73+
except ValueError:
74+
print("Invalid input! Please enter a valid number.")

0 commit comments

Comments
 (0)