+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def init_mowmaster():\n",
+ " return {'x': 0, 'y': 0, 'd': 90}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Execute the instructions. Do them one at a time, updating the mowmaster for each one.\n",
+ "\n",
+ "(Can you see an accumulator pattern again?)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def execute(mowmaster, instructions, debug=False):\n",
+ " for instruction in instructions:\n",
+ " mowmaster = execute_one(mowmaster, instruction, debug=debug)\n",
+ " return mowmaster"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Execute one instruction. If it starts `C` or `A`, turn; if it starts `F`, move forward. Ignore all other instructions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def execute_one(mowmaster, instruction, debug=False):\n",
+ " if instruction == 'C':\n",
+ " mowmaster['d'] = (mowmaster['d'] + 90) % 360 # Use the modulus operator to keep the angle in the range 0--360\n",
+ " elif instruction == 'A':\n",
+ " mowmaster['d'] = (mowmaster['d'] - 90) % 360\n",
+ " elif instruction.startswith('F'):\n",
+ " mowmaster = move(mowmaster, int(instruction[1:]))\n",
+ " if debug: \n",
+ " print(instruction, mowmaster)\n",
+ " return mowmaster"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The movement. Update `x` or `y` depending on the direction."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,