Py.Cafe

SaicharanRitwik39/

CollatzConjecture_Visualizer

Visualizing Collatz Conjecture

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import solara
import matplotlib.pyplot as plt
import networkx as nx

def collatz_sequence(n):
    sequence = [n]
    while n!=1:
        if n%2==0:
            n=n//2
        else:
            n=3*n+1
        sequence.append(n)
    return sequence

def collatz_tree(n):
    G = nx.DiGraph()
    G.add_node(n)
    nodes = [n]
    
    while nodes:
        current = nodes.pop(0)
        if current!=1:
            if current%2==0:
                next_num=current//2
            else:
                next_num =3 * current + 1
            G.add_node(next_num)
            G.add_edge(current, next_num)
            nodes.append(next_num)
    return G    

def plot_collatz(n):
    sequence = collatz_sequence(n)
    plt.figure(figsize=(10, 6))
    plt.plot(sequence, marker='o')
    plt.title(f'Collatz Conjecture Sequence for {n}')
    plt.xlabel('Step')
    plt.ylabel('Value')
    plt.grid(True)
    plt.xticks(range(len(sequence)))
    plt.show()    

def hierarchical_layout(G, root):
    pos = {}
    level = 0
    next_level_nodes = [root]
    
    while next_level_nodes:
        current_level_nodes = next_level_nodes
        next_level_nodes = []
        for i, node in enumerate(current_level_nodes):
            pos[node] = (i, -level)
            next_level_nodes.extend(G.successors(node))
        level += 1
    return pos    

def plot_collatz_tree(n):
    G = collatz_tree(n)
    pos = nx.spring_layout(G)
    plt.figure(figsize=(12, 8))
    nx.draw(G, pos, with_labels=True, node_size=500, node_color="lightblue", font_size=10, font_weight="bold", arrowsize=20)
    plt.title(f'Collatz Conjecture Tree for {n}')
    plt.show()    

@solara.component
def Page():
    int_value = solara.reactive(42)
    continuous_update = solara.reactive(True)   
    solara.InputInt("Enter an integer number", value=int_value, continuous_update=continuous_update.value)
    plot_collatz(int_value.value)
    plot_collatz_tree(int_value.value)