Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +172 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,174 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import time
|
| 3 |
+
import random
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from matplotlib.animation import FuncAnimation
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
# Set page config
|
| 9 |
+
st.set_page_config(page_title="Insertion Sort Visualizer", layout="centered")
|
| 10 |
+
st.title("🔄 Insertion Sort Algorithm Visualizer")
|
| 11 |
+
st.markdown("Watch how Insertion Sort builds a sorted array one element at a time!")
|
| 12 |
+
|
| 13 |
+
# Sidebar controls
|
| 14 |
+
st.sidebar.header("Controls")
|
| 15 |
+
array_size = st.sidebar.slider("Array Size", min_value=5, max_value=50, value=20)
|
| 16 |
+
speed = st.sidebar.slider("Animation Speed (seconds)", min_value=0.1, max_value=2.0, value=0.5, step=0.1)
|
| 17 |
+
|
| 18 |
+
# Generate random array
|
| 19 |
+
if st.sidebar.button("Generate New Array"):
|
| 20 |
+
st.session_state.array = random.sample(range(1, 100), array_size)
|
| 21 |
+
st.session_state.history = []
|
| 22 |
+
st.session_state.steps = []
|
| 23 |
+
st.rerun()
|
| 24 |
+
|
| 25 |
+
# Initialize array in session state
|
| 26 |
+
if "array" not in st.session_state:
|
| 27 |
+
st.session_state.array = random.sample(range(1, 100), array_size)
|
| 28 |
+
st.session_state.history = []
|
| 29 |
+
st.session_state.steps = []
|
| 30 |
+
|
| 31 |
+
array = st.session_state.array.copy()
|
| 32 |
+
|
| 33 |
+
# Insertion Sort with step recording
|
| 34 |
+
def insertion_sort_with_steps(arr):
|
| 35 |
+
steps = []
|
| 36 |
+
history = []
|
| 37 |
+
arr = arr.copy()
|
| 38 |
+
|
| 39 |
+
for i in range(1, len(arr)):
|
| 40 |
+
key = arr[i]
|
| 41 |
+
j = i - 1
|
| 42 |
+
|
| 43 |
+
# Record current state
|
| 44 |
+
history.append(arr.copy())
|
| 45 |
+
steps.append({
|
| 46 |
+
'comparing': i,
|
| 47 |
+
'key': key,
|
| 48 |
+
'action': f"Pick {key} and insert into sorted portion"
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
while j >= 0 and arr[j] > key:
|
| 52 |
+
arr[j + 1] = arr[j]
|
| 53 |
+
j -= 1
|
| 54 |
+
|
| 55 |
+
# Record shift
|
| 56 |
+
history.append(arr.copy())
|
| 57 |
+
steps.append({
|
| 58 |
+
'comparing': j + 1,
|
| 59 |
+
'inserting': i,
|
| 60 |
+
'key': key,
|
| 61 |
+
'action': f"Shift {arr[j+1]} right"
|
| 62 |
+
})
|
| 63 |
+
|
| 64 |
+
arr[j + 1] = key
|
| 65 |
+
|
| 66 |
+
# Record after insertion
|
| 67 |
+
history.append(arr.copy())
|
| 68 |
+
steps.append({
|
| 69 |
+
'inserted': j + 1,
|
| 70 |
+
'key': key,
|
| 71 |
+
'action': f"Insert {key} at position {j+1}"
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# Final sorted array
|
| 75 |
+
history.append(arr.copy())
|
| 76 |
+
steps.append({'action': "Sorting Complete! 🎉", 'sorted': True})
|
| 77 |
+
|
| 78 |
+
return history, steps
|
| 79 |
+
|
| 80 |
+
# Run sorting only when needed
|
| 81 |
+
if st.button("Start Sorting") or st.session_state.get("running", False):
|
| 82 |
+
if not st.session_state.history:
|
| 83 |
+
with st.spinner("Running Insertion Sort..."):
|
| 84 |
+
history, steps = insertion_sort_with_steps(st.session_state.array)
|
| 85 |
+
st.session_state.history = history
|
| 86 |
+
st.session_state.steps = steps
|
| 87 |
+
st.session_state.current_step = 0
|
| 88 |
+
st.session_state.running = True
|
| 89 |
+
|
| 90 |
+
# Animation placeholder
|
| 91 |
+
chart = st.empty()
|
| 92 |
+
info = st.empty()
|
| 93 |
+
progress = st.progress(0)
|
| 94 |
+
|
| 95 |
+
# Animation loop
|
| 96 |
+
for idx, (state, step) in enumerate(zip(st.session_state.history, st.session_state.steps)):
|
| 97 |
+
st.session_state.current_step = idx
|
| 98 |
+
|
| 99 |
+
# Update progress
|
| 100 |
+
progress.progress((idx + 1) / len(st.session_state.history))
|
| 101 |
+
|
| 102 |
+
# Create bar plot
|
| 103 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 104 |
+
bars = ax.bar(range(len(state)), state, color='skyblue', edgecolor='black')
|
| 105 |
+
|
| 106 |
+
# Highlight current key and sorted portion
|
| 107 |
+
if 'comparing' in step:
|
| 108 |
+
bars[step['comparing']].set_color('orange')
|
| 109 |
+
if 'inserted' in step:
|
| 110 |
+
bars[step['inserted']].set_color('green')
|
| 111 |
+
if 'inserting' in step:
|
| 112 |
+
bars[step['inserting']].set_color('red')
|
| 113 |
+
|
| 114 |
+
# Color the sorted portion (left part)
|
| 115 |
+
sorted_until = 0
|
| 116 |
+
for s in st.session_state.steps[:idx]:
|
| 117 |
+
if 'inserted' in s:
|
| 118 |
+
sorted_until = max(sorted_until, s['inserted'] + 1)
|
| 119 |
+
for i in range(sorted_until):
|
| 120 |
+
bars[i].set_color('#90EE90') # light green for sorted
|
| 121 |
+
|
| 122 |
+
ax.set_title("Insertion Sort Visualization", fontsize=16, fontweight='bold')
|
| 123 |
+
ax.set_xlabel("Index")
|
| 124 |
+
ax.set_ylabel("Value")
|
| 125 |
+
ax.set_xlim(-0.5, len(state) - 0.5)
|
| 126 |
+
ax.set_ylim(0, max(state) * 1.1)
|
| 127 |
+
|
| 128 |
+
# Add step description
|
| 129 |
+
action_text = step.get('action', 'Processing...')
|
| 130 |
+
info.markdown(f"**Step {idx + 1}/{len(st.session_state.history)}**: {action_text}")
|
| 131 |
+
|
| 132 |
+
chart.pyplot(fig)
|
| 133 |
+
plt.close(fig)
|
| 134 |
+
|
| 135 |
+
time.sleep(speed)
|
| 136 |
+
|
| 137 |
+
st.success("Insertion Sort Completed!")
|
| 138 |
+
st.balloons()
|
| 139 |
+
st.session_state.running = False
|
| 140 |
+
|
| 141 |
+
# Display current array
|
| 142 |
+
st.subheader("Current Array")
|
| 143 |
+
cols = st.columns(len(array))
|
| 144 |
+
for i, val in enumerate(array):
|
| 145 |
+
cols[i].metric(label=f"Index {i}", value=val)
|
| 146 |
+
|
| 147 |
+
# Show algorithm explanation
|
| 148 |
+
with st.expander("How Insertion Sort Works"):
|
| 149 |
+
st.markdown("""
|
| 150 |
+
### Insertion Sort Algorithm
|
| 151 |
+
|
| 152 |
+
Insertion Sort builds the final sorted array one item at a time.
|
| 153 |
+
|
| 154 |
+
**Steps:**
|
| 155 |
+
1. Start with the second element (index 1)
|
| 156 |
+
2. Compare it with elements on its left
|
| 157 |
+
3. Shift larger elements one position to the right
|
| 158 |
+
4. Insert the element in its correct position
|
| 159 |
+
5. Repeat until the entire array is sorted
|
| 160 |
+
|
| 161 |
+
**Time Complexity:**
|
| 162 |
+
- Best Case: O(n) → Already sorted
|
| 163 |
+
- Average/Worst Case: O(n²)
|
| 164 |
+
|
| 165 |
+
**Great for:** Small datasets or nearly sorted arrays!
|
| 166 |
+
""")
|
| 167 |
|
| 168 |
+
# Reset button
|
| 169 |
+
if st.button("Reset"):
|
| 170 |
+
st.session_state.array = random.sample(range(1, 100), array_size)
|
| 171 |
+
st.session_state.history = []
|
| 172 |
+
st.session_state.steps = []
|
| 173 |
+
st.session_state.running = False
|
| 174 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|