12 "from IPython.display import clear_output\n",
13 "from PIL import Image, ImageDraw, ImageColor, ImageFont"
18 "execution_count": 58,
29 "execution_count": 59,
33 "initial_items = [int((float(i) * RANGE) / float(COLUMNS)) for i in range(COLUMNS)]"
42 "def draw_frame(rows, frame_number, prefix='frame'):\n",
43 " im = Image.new('RGB', (COLUMNS * 1, ROWS * 1))\n",
45 " draw = ImageDraw.Draw(im)\n",
46 " for r in range(len(rows)):\n",
47 " if frame_number >= len(rows[r]):\n",
48 " row = rows[r][-1]\n",
50 " row = rows[r][frame_number]\n",
51 "# for (r, row) in enumerate(grid):\n",
52 " for (c, cell) in enumerate(row):\n",
56 " draw.rectangle([rx, ry, rx + 1, ry + 1], \n",
57 " fill=ImageColor.getrgb(\"hsl({}, 100%, 50%)\".format(cell)))\n",
59 " im.save('{}{:04}.png'.format(prefix, frame_number), 'PNG')"
64 "execution_count": 42,
68 "def insertsort_step(items, sorted_limit):\n",
69 " inserting = items[sorted_limit]\n",
70 " i = len([item for item in items[:sorted_limit] if item < inserting])\n",
71 "# print('sl = {}, i = {}; items = {}; slices {} {} {} {}'.format(sorted_limit, i, items, items[:i], inserting, items[i:sorted_limit], items[sorted_limit + 1:]))\n",
72 " items = items[:i] + [inserting] + items[i:sorted_limit] + items[sorted_limit + 1:]\n",
78 "execution_count": 13,
87 "execution_count": 13,
89 "output_type": "execute_result"
98 "execution_count": 35,
102 "def insertsort(items, step_history):\n",
103 " for sorted_limit in range(1, len(items)):\n",
104 " step_history += [items[:]]\n",
105 " items = insertsort_step(items, sorted_limit)\n",
106 " step_history += [items[:]]"
111 "execution_count": 60,
116 "for _ in range(ROWS):\n",
117 " items = initial_items[:]\n",
118 " random.shuffle(items)\n",
119 " step_history = []\n",
120 " insertsort(items, step_history)\n",
121 " histories += [step_history]"
126 "execution_count": 50,
135 "execution_count": 46,
181 "execution_count": 46,
183 "output_type": "execute_result"
192 "execution_count": 53,
201 "execution_count": 53,
203 "output_type": "execute_result"
212 "execution_count": 61,
221 "execution_count": null,
225 "for frame_n in range(max(len(h) for h in histories)):\n",
226 " draw_frame(histories, frame_n, prefix='insertsort')"
231 "execution_count": 65,
240 "execution_count": 65,
242 "output_type": "execute_result"
251 "execution_count": null,
257 "! apngasm all-insertsort.png insertsort*png 1 10"
262 "execution_count": null,
270 "display_name": "Python 3",
271 "language": "python",
279 "file_extension": ".py",
280 "mimetype": "text/x-python",
282 "nbconvert_exporter": "python",
283 "pygments_lexer": "ipython3",