{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Q 1 (function practice)\n", "\n", "Let's practice functions. Here's a simple function that takes a string and returns a list of all the 4 letter words:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def four_letter_words(message):\n", " words = message.split()\n", " four_letters = [w for w in words if len(w) == 4]\n", " return four_letters" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['over', 'lazy']\n" ] } ], "source": [ "message = \"The quick brown fox jumps over the lazy dog\"\n", "print(four_letter_words(message))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write a version of this function that takes a second argument, n, that is the word length we want to search for" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q 2 (primes)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A prime number is divisible only by 1 and itself. We want to write a function that takes a positive integer, n, and finds all of the primes up to that number.\n", "\n", "A simple (although not very fast) way to find the primes is to start at 1, and build a list of primes by checking if the current number is divisible by any of the previously found primes. If it is not divisible by any earlier primes, then it is a prime.\n", "\n", "The modulus operator, `%` could be helpful here." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 3, 5, 7]\n", "n must be an integer\n" ] }, { "data": { "text/plain": [ "[]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q 3 (exceptions for error handling)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We want to safely convert a string into a float, int, or leave it as a string, depending on its contents. As we've already seen, python provides `float()` and `int()` functions for this:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.0 \n" ] } ], "source": [ "a = \"2.0\"\n", "b = float(a)\n", "print(b, type(b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But these throw exceptions if the conversion is not possible" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "could not convert string to float: 'this is a string'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"this is a string\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: could not convert string to float: 'this is a string'" ] } ], "source": [ "a = \"this is a string\"\n", "b = float(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = \"1.0\"\n", "b = int(a)\n", "print(b, type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b = float(a)\n", "print(b, type(b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that an int can be converted to a float, but if you convert a float to an int, you rise losing significant digits. A string cannot be converted to either.\n", "\n", "### your task\n", "\n", "Write a function, `convert_type(a)` that takes a string `a`, and converts it to a float if it is a number with a decimal point, an int if it is an integer, or leaves it as a string otherwise, and returns the result. You'll want to use exceptions to prevent the code from aborting." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#def convert_type(a):\n", "# \"\"\"input: a a string\n", "# output: if 'a' int -->int(a)\n", "# if 'a' float-->float(a)\n", "# if 'a' string--> a\"\"\"\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Q 4 (tic-tac-toe)\n", "\n", "Here we'll write a simple tic-tac-toe game that 2 players can play. First we'll create a string that represents our game board:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "board = \"\"\"\n", " {s1:^3} | {s2:^3} | {s3:^3}\n", "-----+-----+-----\n", " {s4:^3} | {s5:^3} | {s6:^3}\n", "-----+-----+----- 123\n", " {s7:^3} | {s8:^3} | {s9:^3} 456\n", " 789 \n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This board will look a little funny if we just print it—the spacing is set to look right when we replace the `{}` with `x` or `o`" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " {s1:^3} | {s2:^3} | {s3:^3}\n", "-----+-----+-----\n", " {s4:^3} | {s5:^3} | {s6:^3}\n", "-----+-----+----- 123\n", " {s7:^3} | {s8:^3} | {s9:^3} 456\n", " 789 \n", "\n" ] } ], "source": [ "print(board)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and well use a dictionary to denote the status of each square, \"x\", \"o\", or empty, \"\"" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'s1': '',\n", " 's2': '',\n", " 's3': '',\n", " 's4': '',\n", " 's5': '',\n", " 's6': '',\n", " 's7': '',\n", " 's8': '',\n", " 's9': ''}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "play = {}\n", "\n", "def initialize_board(play):\n", " for n in range(9):\n", " play[\"s{}\".format(n+1)] = \"\"\n", "\n", "initialize_board(play)\n", "play" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that our `{}` placeholders in the `board` string have identifiers (the numbers in the `{}`). We can use these to match the variables we want to print to the placeholder in the string, regardless of the order in the `format()`" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 1\n" ] } ], "source": [ "a = \"{s1:} {s2:}\".format(s2=1, s1=2)\n", "print(a)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's an easy way to add the values of our dictionary to the appropriate squares in our game board. First note that each of the {} is labeled with a number that matches the keys in our dictionary. Python provides a way to unpack a dictionary into labeled arguments, using **\n", "\n", "This lets us to write a function to show the tic-tac-toe board." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " | | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n" ] } ], "source": [ "def show_board(play):\n", " \"\"\" display the playing board. \n", " We take a dictionary with the current state of the board\n", " We rely on the board string to be a global variable\"\"\"\n", " print(board.format(**play))\n", " \n", "show_board(play)\n", "\n", "#if play['s1']==play['s2']==play['s3']=='x': \n", "# print('helo')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we need a function that asks a player for a move:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "def get_move(n, xo, play):\n", " \"\"\" ask the current player, n, to make a move -- make sure the square was not \n", " already played. xo is a string of the character (x or o) we will place in\n", " the desired square \"\"\"\n", " valid_move = False\n", " while not valid_move:\n", " idx = input(\"player {}, enter your move (1-9)\".format(n))\n", " if play[\"s{}\".format(idx)] == \"\":\n", " valid_move = True\n", " else:\n", " print(\"invalid: {}\".format(play[\"s{}\".format(idx)]))\n", " \n", " play[\"s{}\".format(idx)] = xo\n", " \n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function get_move in module __main__:\n", "\n", "get_move(n, xo, play)\n", " ask the current player, n, to make a move -- make sure the square was not \n", " already played. xo is a string of the character (x or o) we will place in\n", " the desired square\n", "\n" ] } ], "source": [ "help(get_move)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We also need a function that checks if a player has already made a winning move after its turn" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "def check_win(play):\n", " \"\"\"Recevies the game board and checks if someone has already won the game\n", " Parameters: \n", " -----------\n", " Play: {dict} The board game\n", " Returns:\n", " -------\n", " win: Logical\n", " true is someone has won\"\"\"\n", " # lets create an internal copy of play\n", " win = False\n", " if play['s1']==play['s2']==play['s3']==('x'or'o'):\n", " win = True\n", " elif play['s4']==play['s5']==play['s6']==('x'or'o'):\n", " win = True\n", " elif play['s7']==play['s8']==play['s9']==('x'or'o'):\n", " win = True\n", " elif play['s1']==play['s4']==play['s7']==('x'or'o'):\n", " win = True \n", " elif play['s5']==play['s2']==play['s8']==('x'or'o'):\n", " win = True\n", " elif play['s9']==play['s6']==play['s3']==('x'or'o'):\n", " win = True \n", " elif play['s5']==play['s7']==play['s3']==('x'or'o'):\n", " win = True\n", " elif play['s1']==play['s5']==play['s9']==('x'or'o'):\n", " win = True \n", " return win " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### your task\n", "\n", "Using the functions defined above\n", " * `initialize_board()`\n", " * `show_board()`\n", " * `get_move()`\n", " * `check_win()`\n", "\n", "fill in the function `play_game()` below to complete the game, asking for the moves one at a time, alternating between player 1 and 2" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "\n", "def play_game():\n", " \"\"\" play a game of tic-tac-toe \"\"\"\n", " board = \"\"\"\n", " {s1:^3} | {s2:^3} | {s3:^3}\n", "-----+-----+-----\n", " {s4:^3} | {s5:^3} | {s6:^3}\n", "-----+-----+----- 123\n", " {s7:^3} | {s8:^3} | {s9:^3} 456\n", " 789 \n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " | | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)1\n", "\n", " x | | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 2, enter your move (1-9)2\n", "\n", " x | o | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)4\n", "\n", " x | o | \n", "-----+-----+-----\n", " x | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 2, enter your move (1-9)5\n", "\n", " x | o | \n", "-----+-----+-----\n", " x | o | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)7\n", "\n", " x | o | \n", "-----+-----+-----\n", " x | o | \n", "-----+-----+----- 123\n", " x | | 456\n", " 789 \n", "\n", "Winner is player 1\n" ] } ], "source": [ "play_game()" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", " | | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)1\n", "\n", " x | | \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 2, enter your move (1-9)3\n", "\n", " x | | o \n", "-----+-----+-----\n", " | | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)5\n", "\n", " x | | o \n", "-----+-----+-----\n", " | x | \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 2, enter your move (1-9)6\n", "\n", " x | | o \n", "-----+-----+-----\n", " | x | o \n", "-----+-----+----- 123\n", " | | 456\n", " 789 \n", "\n", "player 1, enter your move (1-9)9\n", "\n", " x | | o \n", "-----+-----+-----\n", " | x | o \n", "-----+-----+----- 123\n", " | | x 456\n", " 789 \n", "\n", "player 1 wins the game\n" ] } ], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }