Skip to content

Commit f8c3b73

Browse files
author
Susannah Klaneček
committed
Add Python grid demo (insertion sort)
1 parent a8e1a5a commit f8c3b73

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

demos/python/insertion_sort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""Python demo for sorting using VS Code Debug Visualizer."""
2+
import json
3+
4+
5+
def serialize(arr):
6+
"""Serialize an array into a format the visualizer can understand."""
7+
formatted = {
8+
"kind": {"grid": True},
9+
"rows": [
10+
{
11+
"columns": [
12+
{"content": str(value), "tag": str(value)} for value in arr
13+
],
14+
}
15+
],
16+
}
17+
return json.dumps(formatted)
18+
19+
20+
arr = [6, 9, 3, 12, 1, 11, 5, 13, 8, 14, 2, 4, 10, 0, 7]
21+
22+
# Put serialized into the Debug Visualizer console
23+
serialized = serialize(arr)
24+
25+
# Set a breakpoint on the line below and go through the code in debug mode to
26+
# watch it update
27+
for target_idx in range(1, len(arr)):
28+
target_value = arr[target_idx]
29+
compare_idx = target_idx - 1
30+
31+
while compare_idx >= 0 and arr[compare_idx] > target_value:
32+
arr[compare_idx + 1] = arr[compare_idx]
33+
serialized = serialize(arr)
34+
compare_idx -= 1
35+
36+
arr[compare_idx + 1] = target_value
37+
serialized = serialize(arr)
38+
39+
assert arr == sorted(arr)

0 commit comments

Comments
 (0)