From f8c3b73d4fd2445df1581cea4010e77f2d83c468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Susannah=20Klane=C4=8Dek?= Date: Mon, 31 Aug 2020 17:28:54 -0400 Subject: [PATCH] Add Python grid demo (insertion sort) --- demos/python/insertion_sort.py | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 demos/python/insertion_sort.py diff --git a/demos/python/insertion_sort.py b/demos/python/insertion_sort.py new file mode 100644 index 0000000..4bba40b --- /dev/null +++ b/demos/python/insertion_sort.py @@ -0,0 +1,39 @@ +"""Python demo for sorting using VS Code Debug Visualizer.""" +import json + + +def serialize(arr): + """Serialize an array into a format the visualizer can understand.""" + formatted = { + "kind": {"grid": True}, + "rows": [ + { + "columns": [ + {"content": str(value), "tag": str(value)} for value in arr + ], + } + ], + } + return json.dumps(formatted) + + +arr = [6, 9, 3, 12, 1, 11, 5, 13, 8, 14, 2, 4, 10, 0, 7] + +# Put serialized into the Debug Visualizer console +serialized = serialize(arr) + +# Set a breakpoint on the line below and go through the code in debug mode to +# watch it update +for target_idx in range(1, len(arr)): + target_value = arr[target_idx] + compare_idx = target_idx - 1 + + while compare_idx >= 0 and arr[compare_idx] > target_value: + arr[compare_idx + 1] = arr[compare_idx] + serialized = serialize(arr) + compare_idx -= 1 + + arr[compare_idx + 1] = target_value + serialized = serialize(arr) + +assert arr == sorted(arr)