9 "instructions = [l.strip() for l in open('../../data/01-mowmaster.txt')]"
13 "cell_type": "markdown",
32 "output_type": "execute_result"
36 "sum(1 for i in instructions if not i.startswith('#'))"
40 "cell_type": "markdown",
59 "output_type": "execute_result"
63 "sum(1 for i in open('../../data/01-mowmaster.txt') if not i.startswith('#'))"
79 "output_type": "execute_result"
83 "sum(1 for i in instructions if i.startswith('#'))"
99 "output_type": "execute_result"
107 "cell_type": "markdown",
112 "I have the `mower` as an \"object\" storing its state. (In this case, the mower is a `dict` and the state is just its location and direction.) As each instruction is executed, the mower is updated."
116 "cell_type": "markdown",
119 "An initial mower. The initial location and direction don't matter in this case, so I choose a location that's easy and an arbitrary location."
124 "execution_count": 12,
128 "def init_mowmaster():\n",
129 " return {'x': 0, 'y': 0, 'd': 90}"
133 "cell_type": "markdown",
136 "Execute the instructions. If it starts `C` or `A`, turn; if it starts `F`, move forward. Ignore all other instructions."
141 "execution_count": 13,
145 "def execute(mowmaster, instructions, debug=False):\n",
146 " for instruction in instructions:\n",
147 " if instruction == 'C':\n",
148 " mowmaster['d'] = (mowmaster['d'] + 90) % 360 # Use the modul\n",
149 " elif instruction == 'A':\n",
150 " mowmaster['d'] = (mowmaster['d'] - 90) % 360\n",
151 " elif instruction.startswith('F'):\n",
152 " mowmaster = move(mowmaster, int(instruction[1:]))\n",
154 " print(instruction, mowmaster)\n",
159 "cell_type": "markdown",
167 "execution_count": 7,
171 "def move(mower, distance):\n",
172 " if mower['d'] == 0:\n",
173 " mower['y'] += distance\n",
174 " elif mower['d'] == 90:\n",
175 " mower['x'] += distance\n",
176 " elif mower['d'] == 180:\n",
177 " mower['y'] -= distance\n",
178 " elif mower['d'] == 270:\n",
179 " mower['x'] -= distance\n",
181 " raise ValueError\n",
187 "execution_count": 16,
191 "def mowmaster_distance(mw):\n",
192 " return abs(mw['x']) + abs(mw['y'])"
197 "execution_count": 18,
206 "execution_count": 18,
208 "output_type": "execute_result"
212 "mw = init_mowmaster()\n",
213 "execute(mw, instructions)\n",
214 "mowmaster_distance(mw)"
219 "execution_count": null,
227 "display_name": "Python 3",
228 "language": "python",
236 "file_extension": ".py",
237 "mimetype": "text/x-python",
239 "nbconvert_exporter": "python",
240 "pygments_lexer": "ipython3",