diff --git a/.DS_Store b/.DS_Store index 7372fdb..c3c8bd5 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Week_02/.DS_Store b/Week_02/.DS_Store new file mode 100644 index 0000000..108e25d Binary files /dev/null and b/Week_02/.DS_Store differ diff --git a/Week_02/.ipynb_checkpoints/FlippingCoinExample-checkpoint.ipynb b/Week_02/.ipynb_checkpoints/FlippingCoinExample-checkpoint.ipynb new file mode 100644 index 0000000..7b3f2ad --- /dev/null +++ b/Week_02/.ipynb_checkpoints/FlippingCoinExample-checkpoint.ipynb @@ -0,0 +1,101 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Flipping a coin 10 times! " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Heads!\n", + "\n", + "Tails!\n", + "\n", + "Tails!\n", + "\n", + "Tails!\n", + "\n", + "Tails!\n", + "\n", + "Heads!\n", + "\n", + "Heads!\n", + "\n", + "Tails!\n", + "\n", + "Tails!\n", + "\n", + "Heads!\n", + "\n", + "\n", + "Okay, you flipped heads 4 times \n", + "\n", + "and you flipped tails 6 times \n" + ] + } + ], + "source": [ + "import random\n", + "\n", + "total_heads = 0\n", + "total_tails = 0\n", + "count = 0\n", + "\n", + "\n", + "while count < 10:\n", + "\n", + " coin = random.randint(1, 2)\n", + "\n", + " if coin == 1:\n", + " print(\"Heads!\\n\")\n", + " total_heads += 1\n", + " count += 1\n", + "\n", + " elif coin == 2:\n", + " print(\"Tails!\\n\")\n", + " total_tails += 1\n", + " count += 1\n", + "\n", + "print(\"\\nOkay, you flipped heads\", total_heads, \"times \")\n", + "print(\"\\nand you flipped tails\", total_tails, \"times \")" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb b/Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb new file mode 100644 index 0000000..9c3b3d7 --- /dev/null +++ b/Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb @@ -0,0 +1,1743 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "## Basic Operator with Numbers" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "addition: 3\n", + "subtraction: 7\n", + "multiply: 12\n", + "division: 4.0\n" + ] + } + ], + "source": [ + "addition = 1 + 2\n", + "print( \"addition:\", addition)\n", + "subtraction = 9 - 2\n", + "print(\"subtraction:\", subtraction)\n", + "multiply = 2*6\n", + "print(\"multiply:\" , multiply)\n", + "division = 24 / 6\n", + "print(\"division:\", division)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "remainder: 2\n" + ] + } + ], + "source": [ + "# remainder -the number which is left over in a division in which one quantity does not exactly divide another.\n", + "# so 11/3 = 3 and with remainder of 2 (3*3 =9, 11-9 = 2)\n", + "remainder = 11 % 3\n", + "print(\"remainder:\", remainder)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "squared: 49\n", + "cubed: 8\n", + "exponential: 9765625\n" + ] + } + ], + "source": [ + "squared = 7 ** 2\n", + "cubed = 2 ** 3\n", + "exponential = 5 ** 10\n", + "print(\"squared:\", squared)\n", + "print(\"cubed:\", cubed)\n", + "print(\"exponential:\", exponential)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "quotient: 3\n" + ] + } + ], + "source": [ + "#a result obtained by dividing one quantity by another.\n", + "quotient = 10 // 3 # normally 3.3333 but the floor of 3.333 is 3 \n", + "print (\"quotient:\" , quotient)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +======= +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "## Types" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "### Numbers" +======= + "### (Numbers)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Int\n", + "#### Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length." + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 5, +======= + "execution_count": 1, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, +<<<<<<< HEAD + "execution_count": 5, +======= + "execution_count": 1, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "X = 3\n", + "type(X)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Float\n", + "#### Float, or \"floating point number\" is a number, positive or negative, containing one or more decimals." + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 8, +======= + "execution_count": 2, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a is a: \n", + "b is a: \n", + "c is a: \n", + "value of c is: 10000000.0\n" + ] + } + ], + "source": [ + "a = 3.8\n", + "b = 2.75\n", + "c = 1e7 # Float can also be scientific numbers with an \"e\" to indicate the power of 10.\n", + "print(\"a is a: \", type(a))\n", + "print(\"b is a: \",type(b))\n", + "print(\"c is a: \",type(c))\n", + "\n", + "\n", + "print(\"value of c is:\", c)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Strings & List" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### String\n", + "#### A string in Python is a sequence of characters" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 9, +======= + "execution_count": 3, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "this is a string, strings can be created with quatation marks, single, double or triple!\n" + ] + } + ], + "source": [ + "\"this is a string, strings can be created with quatation marks, single, double or triple!\"\n", + "print (\"this is a string, strings can be created with quatation marks, single, double or triple!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Assign string with a variable" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 5, +======= + "execution_count": 4, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hello world\n" + ] + } + ], + "source": [ + "helloworld = \"hello\" + \" \" + \"world\"\n", + "print(helloworld)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### List\n", + "#### A list is a collection which is ordered and changeable. In Python lists are written with square brackets." + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 3, +======= + "execution_count": 5, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [], + "source": [ + "list_with_words= [\"this\", \"is\", \"a\", \"list\", \"we\", \"created\"]" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 14, +======= + "execution_count": 6, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['this', 'is', 'a', 'list', 'we', 'created']\n" + ] + } + ], + "source": [ + "print(list_with_words)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Acess & navigate your list" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 15, +======= + "execution_count": 7, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "this\n" + ] + } + ], + "source": [ + "print(list_with_words[0]) #in programming, index start with 0 instead of 1, so the first item would be number 0" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 16, +======= + "execution_count": 8, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "created\n" + ] + } + ], + "source": [ + "#print the last item\n", + "print(list_with_words[-1])" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 4, +======= + "execution_count": 9, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "we\n" + ] + } + ], + "source": [ + "#print second last item,\n", + "print(list_with_words[-2])" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 5, +======= + "execution_count": 10, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['is', 'a', 'list']\n" + ] + } + ], + "source": [ + "#print from second item to the 5th item\n", + "print(list_with_words[1:4])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Combine list" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 6, +======= + "execution_count": 11, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "odd_even [1, 3, 5, 7, 2, 4, 6, 8]\n", + "even_odd [2, 4, 6, 8, 1, 3, 5, 7]\n" + ] + } + ], + "source": [ + "even_numbers = [2,4,6,8]\n", + "odd_numbers = [1,3,5,7]\n", + "odd_even = odd_numbers + even_numbers\n", + "even_odd = even_numbers + odd_numbers\n", + "print(\"odd_even\", odd_even)\n", + "print(\"even_odd\", even_odd)" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 7, +======= + "execution_count": 12, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 1, 2, 3, 1, 2, 3]\n" + ] + } + ], + "source": [ + "print([1,2,3] * 3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "## Comparison & Boolean" +======= + "## Basic Operator with Numbers" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 22, +======= + "execution_count": 13, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "True\n" +======= + "addition: 3\n", + "subtraction: 7\n", + "multiply: 12\n", + "division: 4.0\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = 5\n", + "print (x ==5) # == is for comparing values, = is for assigning values" +======= + "addition = 1 + 2\n", + "print( \"addition:\", addition)\n", + "subtraction = 9 - 2\n", + "print(\"subtraction:\", subtraction)\n", + "multiply = 2*6\n", + "print(\"multiply:\" , multiply)\n", + "division = 24 / 6\n", + "print(\"division:\", division)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 6, +======= + "execution_count": 14, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "False\n" +======= + "remainder: 2\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = 5\n", + "print(x!=5) #! is used as negation " +======= + "# remainder -the number which is left over in a division in which one quantity does not exactly divide another.\n", + "# so 11/3 = 3 and with remainder of 2 (3*3 =9, 11-9 = 2)\n", + "remainder = 11 % 3\n", + "print(\"remainder:\", remainder)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 8, +======= + "execution_count": 15, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "True\n" +======= + "squared: 49\n", + "cubed: 8\n", + "exponential: 9765625\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = 5\n", + "\n", + "print(x > 3 and x < 10)" +======= + "squared = 7 ** 2\n", + "cubed = 2 ** 3\n", + "exponential = 5 ** 10\n", + "print(\"squared:\", squared)\n", + "print(\"cubed:\", cubed)\n", + "print(\"exponential:\", exponential)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 9, + "metadata": {}, +======= + "execution_count": 16, + "metadata": { + "scrolled": true + }, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "True\n" +======= + "quotient: 3\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = 5\n", + "\n", + "print(x > 3 or x < 4)" +======= + "#a result obtained by dividing one quantity by another.\n", + "quotient = 10 // 3 # normally 3.3333 but the floor of 3.333 is 3 \n", + "print (\"quotient:\" , quotient)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Short Hand" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 10, +======= + "execution_count": 17, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "False\n" +======= + "8\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = 5\n", + "\n", + "print(not(x > 3 and x < 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Identity Operators" +======= + "x=3\n", + "x+=5 # x=x+5\n", + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "7\n" + ] + } + ], + "source": [ + "y=9\n", + "y-=2 # y=9-2 \n", + "print(y)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 11, +======= + "execution_count": 19, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "False\n", + "True\n", + "False\n" +======= + "6\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x1 = 5\n", + "y1 = 5\n", + "x2 = 'Hello'\n", + "y2 = 'Hello'\n", + "x3 = [1,2,3]\n", + "y3 = [1,2,3]\n", + "\n", + "# Output: False\n", + "print(x1 is not y1)\n", + "\n", + "# Output: True\n", + "print(x2 is y2)\n", + "\n", + "# Output: False\n", + "print(x3 is y3)" +======= + "x=2\n", + "x*=3 # x=2*3 \n", + "print(x)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 12, +======= + "execution_count": 20, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ +<<<<<<< HEAD + "True\n" +======= + "9.0\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + } + ], + "source": [ +<<<<<<< HEAD + "x = [\"apple\", \"banana\"]\n", + "\n", + "print(\"banana\" in x)" +======= + "y = 18\n", + "y/=2 # y=18/2 \n", + "print(y)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Type Convertion / Cast" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 14, +======= + "execution_count": 21, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x: 1\n", + "y: 2\n", + "z: 3\n" + ] + } + ], + "source": [ + "x = int(1) # x will be 1\n", + "y = int(2.8) # y will be 2\n", + "z = int(\"3\") # z will be 3\n", + "print (\"x:\",x)\n", + "print(\"y:\",y) \n", + "print(\"z:\",z)" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 15, +======= + "execution_count": 22, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x: 1.0\n", + "y: 2.8\n", + "z: 3.0\n", + "w: 4.2\n" + ] + } + ], + "source": [ + "x = float(1) # x will be 1.0\n", + "y = float(2.8) # y will be 2.8\n", + "z = float(\"3\") # z will be 3.0\n", + "w = float(\"4.2\") # w will be 4.2\n", + "print (\"x:\",x)\n", + "print(\"y:\",y) \n", + "print(\"z:\",z)\n", + "print(\"w:\",w )" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 16, +======= + "execution_count": 23, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x: s1\n", + "y: 2\n", + "z: 3.0\n" + ] + } + ], + "source": [ + "x = str(\"s1\") # x will be 's1'\n", + "y = str(2) # y will be '2'\n", + "z = str(3.0) # z will be '3.0'\n", + "print (\"x:\",x)\n", + "print(\"y:\",y) \n", + "print(\"z:\",z)" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 13, +======= + "execution_count": 24, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "datatype of num_int: \n", + "datatype of num_flo: \n", + "Value of num_new: 124.23\n", + "datatype of num_new: \n" + ] + } + ], + "source": [ + "num_int = 123\n", + "num_flo = 1.23\n", + "\n", + "num_new = num_int + num_flo\n", + "\n", + "print(\"datatype of num_int:\",type(num_int))\n", + "print(\"datatype of num_flo:\",type(num_flo))\n", + "\n", + "print(\"Value of num_new:\",num_new)\n", + "print(\"datatype of num_new:\",type(num_new))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Changing Types" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### The below code will not work " + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], +======= + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Data type of num_int: \n", + "Data type of num_str: \n" + ] + }, + { + "ename": "TypeError", + "evalue": "unsupported operand type(s) for +: 'int' and 'str'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\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 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Data type of num_str:\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum_str\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnum_int\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0mnum_str\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" + ] + } + ], +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "source": [ + "num_int = 123\n", + "num_str = \"456\"\n", + "\n", + "print(\"Data type of num_int:\",type(num_int))\n", + "print(\"Data type of num_str:\",type(num_str))\n", + "\n", + "print(num_int+num_str)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Using type conversion to make the code below to work" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], +======= + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Data type of num_int: \n", + "Data type of num_str before Type Casting: \n", + "Data type of num_str after Type Casting: \n", + "Sum of num_int and num_str: 579\n", + "Data type of the sum: \n" + ] + } + ], +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "source": [ + "num_int = 123\n", + "num_str = \"456\"\n", + "\n", + "print(\"Data type of num_int:\",type(num_int))\n", + "print(\"Data type of num_str before Type Casting:\",type(num_str))\n", + "\n", + "num_str = int(num_str)\n", + "print(\"Data type of num_str after Type Casting:\",type(num_str))\n", + "\n", + "num_sum = num_int + num_str\n", + "\n", + "print(\"Sum of num_int and num_str:\",num_sum)\n", + "print(\"Data type of the sum:\",type(num_sum))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "## Logical Operations " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Logical operators are the and, or, not operators." + ] + }, + { + "cell_type": "code", + "execution_count": 17, +======= + "## Comparison & Boolean" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "x = 5\n", + "print (x ==5) # == is for comparing values, = is for assigning values" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], + "source": [ + "x = 5\n", + "print(x!=5) #! is used as negation " + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "x = 5\n", + "\n", + "print(x > 3 and x < 10)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "x = 5\n", + "\n", + "print(x > 3 or x < 4)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], + "source": [ + "x = 5\n", + "\n", + "print(not(x > 3 and x < 10))" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "x = 5\n", + "\n", + "print(x>=5)" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], + "source": [ + "x=5\n", + "\n", + "print (x<=4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Logical Operations " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Logical operators are the and, or, not operators." + ] + }, + { + "cell_type": "code", + "execution_count": 34, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x and y is False\n", + "x or y is True\n", + "not x is False\n" + ] + } + ], + "source": [ + "x = True\n", + "y = False\n", + "\n", +<<<<<<< HEAD + "print('x and y is',x and y)\n", + "\n", + "print('x or y is',x or y)\n", + "\n", + "print('not x is',not x)" +======= + "print('x and y is',x and y) # one is true and the other is false, so 'and' is false\n", + "\n", + "print('x or y is',x or y) # one is true, other is false, so 'or' is true \n", + "\n", + "print('not x is',not x) # opposite of true is false " +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Identity operators: \"is not\" and \"is\" " + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], +======= + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "True\n" + ] + } + ], +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "source": [ + "x1 = 5\n", + "y1 = 5\n", + "x2 = 'Hello'\n", + "y2 = 'Hello'\n", +<<<<<<< HEAD + "x3 = [1,2,3]\n", + "y3 = [1,2,3]\n", +======= +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "\n", + "# Output: False\n", + "print(x1 is not y1)\n", + "\n", + "# Output: True\n", +<<<<<<< HEAD + "print(x2 is y2)\n", + "\n", + "# Output: False\n", + "print(x3 is y3)" +======= + "print(x2 is y2)\n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### membership operators: \"not in\" and \"in\" " + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = 'Hello world'\n", + "y = {1:'a',2:'b'}\n", +======= + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n", + "False\n" + ] + } + ], + "source": [ + "x = 'Hello world'\n", +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "\n", + "# Output: True\n", + "print('H' in x)\n", + "\n", +<<<<<<< HEAD + "# Output: True\n", + "print('hello' not in x)\n", + "\n", + "# Output: True\n", + "print(1 in y)\n", + "\n", + "# Output: False\n", + "print('a' in y)" +======= + "# Output: False\n", + "print('hello' in x) #this is because the \"H\" is capitalized\n", + "\n", + "# Output: True\n", + "print('Hello' not in x) \n" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### If Statements" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 4, +======= + "execution_count": 37, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition not met\n" + ] + } + ], + "source": [ + "x = False\n", +<<<<<<< HEAD + "if x : # this if x is true \n", +======= + "if x: # this means if x is true \n", +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": 3, +======= + "execution_count": 38, +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition met\n" + ] + } + ], + "source": [ + "x = False\n", +<<<<<<< HEAD + "if not x : # this means condition is true because not false is true \n", +======= + "if not x: # this means condition is true because 'not false' is true \n", +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { +<<<<<<< HEAD + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## This and that or something else\n" +======= + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is less than y\n" + ] + } + ], + "source": [ + "x = 10 \n", + "y = 20\n", + "\n", + "if x < y:\n", + " print(\"x is less than y\")\n", + "else: \n", + " print(\"x is greater than y \")" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", +<<<<<<< HEAD + "Two easy to understand operators are and and or. They do exactly what they sound like:" +======= + "### Two easy to understand operators are and and or. They do exactly what they sound like:" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], +======= + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition met\n", + "condition met\n" + ] + } + ], +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + "source": [ + "if 1 < 2 and 4 > 2:\n", + " print(\"condition met\")\n", + "\n", +<<<<<<< HEAD + "if 1 > 2 and 4 < 10:x\n", + " print(\"condition not met\")\n", + "\n", + "if 4 < 10 or 1 < 2:\n", +======= + "if 4 < 10 or 1 > 2:\n", +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + " print(\"condition met\")" + ] + }, + { +<<<<<<< HEAD + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### For loops " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = ['yellow', 'blue', 'red']\n", + "for i in a:\n", + " print(i)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Avoid Infinity loops \n", + "## while loops" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = 1\n", + "while x <= 5:\n", + " print(x)\n", + " x += 1" +======= + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [], + "source": [ + "if 1 > 2 and 4 < 10:\n", + " print(\"condition not met\") # this will not print anything bc condition is not met " +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "### using breaks" +======= + "#### nested IF statements" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "i = 1\n", + "while i < 6:\n", + " print(i)\n", + " if i == 3:\n", + " break\n", + " i += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## if statements " +======= + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "X is above ten,\n", + "and also above 20!\n" + ] + } + ], + "source": [ + "x = 41\n", + "\n", + "if x > 10:\n", + " print(\"X is above ten,\")\n", + " if x > 20:\n", + " print(\"and also above 20!\")\n", + " else:\n", + " print(\"but not above 20.\")" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = 200\n", + "b = 33\n", + "if b > a:\n", + " print(\"b is greater than a\")\n", + "else:\n", + " print(\"b is not greater than a\")" +======= + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "a and b are equal\n" + ] + } + ], + "source": [ + "# use elif for multiple conditions \n", + "\n", + "a = 33\n", + "b = 33\n", + "if b > a:\n", + " print(\"b is greater than a\")\n", + "elif a < b: # elif is shorthand for \"else if\" \n", + " print(\"a is greater than b\")\n", + "elif a == b:\n", + " print(\"a and b are equal\")" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "## Nested if statements " +======= + "### For Loops " +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = 41\n", + "\n", + "if x > 10:\n", + " print(\"Above ten,\")\n", + " if x > 20:\n", + " print(\"and also above 20!\")\n", + " else:\n", + " print(\"but not above 20.\")" +======= + "execution_count": 44, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yellow\n", + "blue\n", + "red\n" + ] + } + ], + "source": [ + "list = ['yellow', 'blue', 'red']\n", + "\n", + "for color in list:\n", + " print(color)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ +<<<<<<< HEAD + "## elif" +======= + "#### Avoid infinte loops " +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "a = 33\n", + "b = 33\n", + "if b > a:\n", + " print(\"b is greater than a\")\n", + "elif a == b:\n", + " print(\"a and b are equal\")" +======= + "execution_count": 45, + "metadata": {}, + "outputs": [], + "source": [ + "# This will go on forever becayse x is ALWAYS equal to one \n", + "\n", + "# x = 1\n", + "# while x < 5:\n", + "# print(x)" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "cell_type": "code", +<<<<<<< HEAD + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "cars = ['audi', 'bmw', 'subaru', 'toyota']\n", + "\n", + "for car in cars:\n", + " if car == 'bmw':\n", + " print(car.upper()) # this is a method, we will discuss this later \n", + " else: \n", + " print(car.title()) # this is a method, we will discuss this later " +======= + "execution_count": 46, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "# This will stop when x is less than or = to 5 because everytime it runs, x goes up by 1 \n", + "x = 1\n", + "while x <= 5:\n", + " print(x)\n", + " x += 1 # x=x+1 \n", + " " +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + ] + }, + { + "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", +<<<<<<< HEAD + "version": "3.7.4" +======= + "version": "3.7.6" +>>>>>>> d9eb427d29bd676d414b63198d2e39daf784bd19 + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_02/Week 2 Math, Logic, Loops.ipynb b/Week_02/Week 2 Math, Logic, Loops.ipynb index e3c2741..1709663 100644 --- a/Week_02/Week 2 Math, Logic, Loops.ipynb +++ b/Week_02/Week 2 Math, Logic, Loops.ipynb @@ -11,7 +11,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Numbers" + "### (Numbers)" ] }, { @@ -1196,7 +1196,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.3" + "version": "3.7.6" } }, "nbformat": 4, diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store new file mode 100644 index 0000000..9e15f5a Binary files /dev/null and b/Week_03/.DS_Store differ diff --git a/Week_03/.gitignore b/Week_03/.gitignore new file mode 100644 index 0000000..82fb2cd --- /dev/null +++ b/Week_03/.gitignore @@ -0,0 +1 @@ +../.DS_Store diff --git a/Week_03/README.md b/Week_03/README.md index fcc9f8b..aa4a96e 100644 --- a/Week_03/README.md +++ b/Week_03/README.md @@ -1 +1,39 @@ ## Week III: Strings, Lists, and Tuples + +#### Topics +- BlackOutTuesday Insta bot with Jason: [nlm-instagram-bot-repo](https://github.com/jasonzli/blm-instagram-bot) + +- Strings, lists and tuples with Anna and Lan +- Raspberry Pi intro with Sven +--- + +#### Repo Directory +- [Cheatsheets](https://github.com/parsons-python-summer-2020/python/tree/master/Week_03/cheatsheets) (textbook-style breakdowns) + - String basics + - List and tuple basics + +- [Class code](https://github.com/parsons-python-summer-2020/python/tree/master/Week_03/class_code) + - Palindrome checker + > a function that checks whether any given string is a palindrome (spelled the same backwards as forwards). + - Mad Libs generator + > an invitation generator that automates creating copies of event invitations. + +- [Exercises](https://github.com/parsons-python-summer-2020/python/tree/master/Week_03/exercises) + - Palindrome checker - extended + - Mad Libs generator - extended + - Lexical richness scorer `Bonus!` +--- + +#### Helpful links +- [String Documentation](https://docs.python.org/2.5/lib/string-methods.html) +- [List Documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists) +- [Tuple Documentation](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) + +--- + +#### class slides +[Week3 google slide](https://docs.google.com/presentation/d/1LOffhetydFlmyiC7BpUwCTuRlyk_CGCLf1qmzvhi6eM/edit?usp=sharing) + + +#### Slack question channel +[#discuss-wk-03](https://parsonspython-spx9490.slack.com/archives/C013VTY849H) diff --git a/Week_03/cheatsheets/README.md b/Week_03/cheatsheets/README.md new file mode 100644 index 0000000..28d4f0b --- /dev/null +++ b/Week_03/cheatsheets/README.md @@ -0,0 +1 @@ +# Commented notebooks with basic information, presented textbook-style. diff --git a/Week_03/cheatsheets/cheatsheet_strings.ipynb b/Week_03/cheatsheets/cheatsheet_strings.ipynb new file mode 100644 index 0000000..2ae2394 --- /dev/null +++ b/Week_03/cheatsheets/cheatsheet_strings.ipynb @@ -0,0 +1,688 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String basics\n", + "\n", + "What is a string?
\n", + "Creating strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What is a string?\n", + "\n", + "A `string` is a sequence of characters written between quotation marks.\n", + "\n", + "Here are a few examples:\n", + "\n", + "```\n", + "my_string = 'abc'\n", + "my_string = 'It was a dark and stormy night.'\n", + "my_string = 'alsdf0898'\n", + "my_string = ' '\n", + "my_string = '\\n'\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

Creating strings

" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, world!\n", + "Hello, world!\n" + ] + } + ], + "source": [ + "## Strings are data surrounded by single or double quotes\n", + "## The following are equivalent:\n", + "\n", + "print('Hello, world!')\n", + "print(\"Hello, world!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (, line 3)", + "output_type": "error", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m print('She was like, 'OMG what?!'')\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "# What happens if you want a quotation mark *inside* of your string?\n", + "\n", + "print('She was like, 'OMG what?!'')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "## To include quotation marks *inside* a string, \n", + "## we have a few options:\n", + "\n", + "# Option 1. Use one type outside, and another type inside.\n", + "\n", + "print('She was like, \"OMG what?!\"')\n", + "print(\"She was like, 'OMG what?!'\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Option 2. Use *escape* characters so that the quotation mark\n", + "# is interpreted as a *string literal*.\n", + "\n", + "print('She was like, \\'OMG what?!\\'')\n", + "print(\"She was like, \\\"OMG what?!\\\"\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# We can point a variable to a string.\n", + "\n", + "my_string = 'I love trucks.'\n", + "print(my_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Manipulating string variables" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I love trucks.\n", + "I love butterflies.\n" + ] + } + ], + "source": [ + "# Strings in Python are *immutable*, meaning the\n", + "# data itself doesn't change. (We will discuss this more later.)\n", + "\n", + "# But we can always redirect a variable (e.g. my_string) to \n", + "# point to a new string.\n", + "\n", + "my_string = 'I love trucks.'\n", + "print(my_string)\n", + "\n", + "my_string = 'I love butterflies.'\n", + "print(my_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I love butterflies and I love trucks.\n" + ] + } + ], + "source": [ + "# We can add strings\n", + "\n", + "my_string = 'I love butterflies ' + 'and I love trucks.'\n", + "print(my_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I love butterflies!!!!! I really do!\n" + ] + } + ], + "source": [ + "# We can add strings to existing strings \n", + "# with a shorthand operator\n", + "\n", + "my_string = 'I love butterflies'\n", + "my_string += '!!!!!'\n", + "my_string += ' I really do!'\n", + "\n", + "print(my_string)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I love butterflies. I love butterflies. I love butterflies. \n" + ] + } + ], + "source": [ + "# We can also multiply strings by an integer!\n", + "\n", + "my_string = 'I love butterflies. ' * 3\n", + "print(my_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Accessing characters" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "l\n" + ] + } + ], + "source": [ + "# Let's jump INTO the string data now.\n", + "# We can access specific characters within a string\n", + "# using an *index*.\n", + "\n", + "# As usual, indexing starts at 0:\n", + "my_string = 'looong table'\n", + "print(my_string[0])" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "e\n" + ] + } + ], + "source": [ + "# We can access the last character using\n", + "# *negative indexing*\n", + "\n", + "my_string = 'looong table'\n", + "print(my_string[-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "table\n" + ] + } + ], + "source": [ + "# We can access a *range* of characters by \n", + "# providing a start and end index.\n", + "\n", + "my_string = 'looong table'\n", + "print(my_string[7:12])" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "looong\n", + "table\n" + ] + } + ], + "source": [ + "# If either the start or end is left undefined,\n", + "# python will assume the start or end.\n", + "\n", + "my_string = 'looong table'\n", + "print(my_string[:6]) # assume [0:6]\n", + "print(my_string[7:]) # assume [6:12]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Docstrings\n", + "\n", + "\"If you violate these conventions, the worst you'll get is some dirty looks.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "HELLO!!!!\n" + ] + } + ], + "source": [ + "# Docstrings are special strings, added to code for legibility.\n", + "# It is convention to use them as the first statement in a\n", + "# module, function, class, or method definition.\n", + "\n", + "# A one-line docstring example, in a function\n", + "def yellHello():\n", + " \"\"\"Print 'hello' in all caps, with exclamation marks.\"\"\"\n", + " print('HELLO!!!!')\n", + "\n", + "yellHello()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "garba\n" + ] + } + ], + "source": [ + "# A multi-line docstring example, in a function\n", + "\n", + "def createUserID(last, first):\n", + " \"\"\"\n", + " Given a full name, return a corresponding user ID. \n", + " \n", + " The user ID is a concatenation of the first\n", + " four letters of the last name followed by the\n", + " first letter of the first name.\n", + " \n", + " Parameters: \n", + " last (string): Last name\n", + " first (string): First name\n", + " \n", + " Returns: \n", + " string: User ID\n", + " \"\"\"\n", + " \n", + " return(last[0:4] + first[0])\n", + "\n", + "userID = createUserID('garbier', 'anna')\n", + "print(userID)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Strings as objects\n", + "\n", + "So far, we've been talking about strings as pieces of data. We are now going to think about them as **String Objects**.\n", + "\n", + "In object oriented programming, objects have two components: properties and methods. Properties are characteristics of the object. Methods are functions that the object can perform.\n", + "\n", + "All strings in python come with built-in methods (i.e. built-in things they can *do*).\n", + "\n", + "The following are just a few smaples. There are [many more](https://www.w3schools.com/python/python_ref_string.asp) to explore." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Convert casing" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "once upon a time...\n", + "ONCE UPON A TIME...\n", + "Once upon a time...\n", + "Once Upon A Time...\n", + "ONcE uPON a time...\n" + ] + } + ], + "source": [ + "# Convert casing\n", + "my_string = \"onCe Upon A TIME...\"\n", + "\n", + "print(my_string.lower()) # Convert all chars to lowercase\n", + "print(my_string.upper()) # Convert all chars to uppercase\n", + "print(my_string.capitalize()) # Convert first char only to uppercase\n", + "print(my_string.title()) # Convert string to title case\n", + "print(my_string.swapcase()) # Swap all uppercase for lowercase and vice-versa" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Clean edges" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "|It was a dark and stormy night... |\n", + "| It was a dark and stormy night...|\n", + "|It was a dark and stormy night...|\n" + ] + } + ], + "source": [ + "# Clean spaces from the edges of string\n", + "my_string = \" It was a dark and stormy night... \"\n", + "\n", + "print(\"|\" + my_string.lstrip() + \"|\") # Strip whitespace from left side of string\n", + "print(\"|\" + my_string.rstrip() + \"|\") # Strip whitespace from right side of string\n", + "print(\"|\" + my_string.strip() + \"|\") # Strip whitespace from both sides of string" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "owza...\n", + "...wowz\n" + ] + } + ], + "source": [ + "# Clean custom character sets from the edges of string\n", + "my_string = \"...wowza...\"\n", + "\n", + "print(my_string.lstrip(\".w\")) # Strip \"w\" and \".\" from left side of string\n", + "print(my_string.rstrip(\"a.\")) # Strip \"a\" and \".\" from right side of string" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "oonnoo boonoonoo\n" + ] + } + ], + "source": [ + "# Replace all instances of a character for another character\n", + "my_string = \"anna banana\"\n", + "\n", + "print(my_string.replace('a', 'oo'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Inspect" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "True\n" + ] + } + ], + "source": [ + "# Inspect the general contents of the string\n", + "my_string = \"garba048\"\n", + "\n", + "print(my_string.isalpha()) # Returns True if contets are all alphabet characters\n", + "print(my_string.isalnum()) # Returns True if contets are all alpha-numeric characters" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "# Inspect the general contents of the string\n", + "my_string = \" \\n\"\n", + "\n", + "print(my_string.isspace()) # Returns True if contets are all whitespace" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\n", + "12\n" + ] + } + ], + "source": [ + "# Search for a match, and return the first index where it is found\n", + "my_string = \"The copiale cipher is an encrypted manuscript...\"\n", + "\n", + "print(my_string.index(\"c\")) # Find the index of the first match\n", + "print(my_string.index(\"cipher\")) # Find the index of the first match" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Normalize length" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "loooooooooooong string\n", + "0000000000short string\n" + ] + } + ], + "source": [ + "# Normalize the length of two strings by adding \"padding\"\n", + "my_long_string = \"loooooooooooong string\"\n", + "my_short_string = \"short string\"\n", + "\n", + "print(my_long_string.zfill(22))\n", + "print(my_short_string.zfill(22))" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "22\n", + "12\n", + "10\n" + ] + } + ], + "source": [ + "# While we're here, let's talk about measuring the length of a string.\n", + "my_long_string = \"loooooooooooong string\"\n", + "my_short_string = \"short string\"\n", + "\n", + "print(len(my_long_string)) # Length of long string\n", + "print(len(my_short_string)) # Length of short string\n", + "print(len(my_long_string) - len(my_short_string)) # Difference in length" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Long string has 22 characters.\n", + "Short string has 12 characters.\n", + "Long string has 10 more characters.\n" + ] + } + ], + "source": [ + "# len() returns an integeger. To integrate integers\n", + "# into strings, we can convert them into strings using str().\n", + "my_long_string = \"loooooooooooong string\"\n", + "my_short_string = \"short string\"\n", + "\n", + "my_long_string_length = len(my_long_string)\n", + "my_short_string_length = len(my_short_string)\n", + "\n", + "print(\"Long string has \" + str(my_long_string_length) + \" characters.\")\n", + "print(\"Short string has \" + str(my_short_string_length) + \" characters.\")\n", + "print(\"Long string has \" + str(my_long_string_length - my_short_string_length) + \" more characters.\")" + ] + } + ], + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/cheatsheets/cheatsheet_tuples_lists.ipynb b/Week_03/cheatsheets/cheatsheet_tuples_lists.ipynb new file mode 100644 index 0000000..447973a --- /dev/null +++ b/Week_03/cheatsheets/cheatsheet_tuples_lists.ipynb @@ -0,0 +1,852 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "

TUPLES & LISTS

\n", + "\n", + "1. [Definitions](#01)\n", + "1. [When to use tuples versus lists?](#02)\n", + "1. [Common methods for both lists and tuples](#03)\n", + "1. [Conversions among lists, tuples and strings](#04)\n", + "1. [Modifying elements with Lists!](#05)\n", + "\n", + "
\n", + "\n", + "\n", + "\n", + "## Definitions\n", + "\n", + "Tuples and lists are both collection data types that store array(s) of data \n", + "\n", + "\n", + "Tuples are immutable lists!\n", + "\n", + "- Tuples are immutable - cannot be changed\n", + " - usually declare with parenthesis ( )\n", + "- Lists are mutable - can be changed\n", + " - usually declare with square brackets [ ]\n", + "- You can do a lot of things to both tuples or lists such as \n", + " - looping \n", + " - iterating\n", + " - accessing\n", + "- There are things you can only do with lists\n", + " - change values of elements\n", + " - reordering\n", + " - Adding/removing elements" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "()\n", + "(1, 2, 3)\n", + "(1, 'Hello', 3.4)\n", + "('sun', [8, 4, 6], (1, 2, 3))\n" + ] + } + ], + "source": [ + "# How to declare a tuple, with parentheses or not, separated by comma\n", + "t1 = 1,3,4,6 # no parentheses is called tuple packing\n", + "t2 = (1,3,4,6)\n", + "print(type(t1))\n", + "print(type(t2))\n", + "\n", + "# Different types of tuples\n", + "\n", + "# Empty tuple\n", + "my_tuple = ()\n", + "print(my_tuple)\n", + "\n", + "# Tuple having integers\n", + "my_tuple = (1, 2, 3)\n", + "print(my_tuple)\n", + "\n", + "# Tuple with mixed datatypes\n", + "my_tuple = (1, \"Hello\", 3.4)\n", + "print(my_tuple)\n", + "\n", + "# nested tuple\n", + "# Although tupels cannot be changed, item of mutable element can be changed\n", + "my_tuple = (\"sun\", [8, 4, 6], (1, 2, 3))\n", + "print(my_tuple)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n" + ] + } + ], + "source": [ + "# Having parentheses is not enough, tuples are actually identified with commas\n", + "tuple_ = (\"hello\")\n", + "print(type(tuple_))\n", + "tuple_ = (\"hello\",)\n", + "print(type(tuple_))" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "[]\n", + "[2, 1, 4]\n", + "[1, 'Hello', 0.2]\n", + "('sun', [8, 4, 6], (1, 2, 3))\n" + ] + } + ], + "source": [ + "# How to declare a list\n", + "li = [1,3,4,6]\n", + "print(type(li))\n", + "\n", + "# Empty list\n", + "my_list = []\n", + "print(my_list)\n", + "\n", + "# List having integers\n", + "my_list = [2,1,4]\n", + "print(my_list)\n", + "\n", + "# List with mixed datatypes\n", + "my_list = [1,\"Hello\",0.2]\n", + "print(my_list)\n", + "\n", + "# Nested Lists\n", + "my_list = (\"sun\", [8, 4, 6], (1, 2, 3))\n", + "print(my_list)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## When would I use tuples rather than lists?\n", + "\n", + "#### general rules for choosing which to use:\n", + "- when you need to modify or change elements, use lists\n", + "- when you only need to iterate/access values, use tuples\n", + "\n", + "#### Benefits of tuples:\n", + "- tuples are less expensive for your program to run as it iterates through all elements faster\n", + "- you cannot change the value of elements nor the order of elements\n", + "- once a tuple is created, you cannot change elements(immutable), add/remove elements\n", + "- if you are only creating collections of data with a fixed value and order, use tuples\n", + "\n", + "#### Benefits of lists\n", + "- you can modify elements, change elements \n", + "- once it's created, you can append, delete, re-order \n", + "\n", + " \n", + "Generally speaking, lists are used more often than tuples." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'tuple' object does not support item assignment", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\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[0;31m# tuples are immutable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mt2\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m2\u001b[0m \u001b[0;31m# this will raise error because you cannot modify it\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" + ] + } + ], + "source": [ + "# tuples are immutable\n", + "t2[1] = 2 # this will raise error because you cannot modify it" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 4, 6]\n", + "[1, 2, 4, 6]\n" + ] + } + ], + "source": [ + "# lists are immutable\n", + "print(li)\n", + "li[1] = 2 # this will change the second element's value to 2\n", + "print(li)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "# Common methods you can use for both tuples and lists\n", + "- you can do a lot of things to both tuples or lists such as \n", + " - [accessing elements](#10)\n", + " - [indexing](#11)\n", + " - [negative indexing](#12)\n", + " - [range of indexes](#13)\n", + " - [iterating/looping](#14)\n", + " - for loop" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "## How to access individual element?\n", + "\n", + "### Indexing\n", + "Let's say you declare a list or tuple, and you need to retrieve the value of specific element:\n", + "- You use square brackets to call out the index number aka the location of the element within the group\n", + "- Every element in a list or a tuple has its ordered position\n", + "- In the programming world, the first element/index starts with 0, not 1!" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(1, 3, 4, 6)\n", + "1\n" + ] + } + ], + "source": [ + "print(t1)\n", + "print(t1[0]) # print only the first element" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 3, 4, 6]\n", + "3 4 6\n" + ] + } + ], + "source": [ + "print(li)\n", + "print(li[1],li[2],li[3]) # [1] is actually the second element" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "ename": "IndexError", + "evalue": "list index out of range", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mli\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mIndexError\u001b[0m: list index out of range" + ] + } + ], + "source": [ + "print(li[4]) # will raise error because [4] is the 5th element" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Negative indexing\n", + "if you want to get the last item of a list/tuple, you can use \"[-num]\"" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'li' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mli\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mli\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# the last element in the list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt1\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# same with tuple\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt1\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mNameError\u001b[0m: name 'li' is not defined" + ] + } + ], + "source": [ + "print(li[3])\n", + "print(li[-1]) # the last element in the list\n", + "print(t1[3]) # same with tuple\n", + "print(t1[-1])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Range of indexes\n", + "if you want a range of elements from a list or tuple" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Design', 'and', 'Technology']\n", + "['Parsons', 'Design', 'and']\n", + "['Technology']\n" + ] + } + ], + "source": [ + "terms = ['Parsons','Design','and','Technology']\n", + "#range outputs the same datatype\n", + "print(terms [1:])\n", + "print(terms [:-1])\n", + "print(terms [-1:])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Iterating/looping\n", + "\n", + "If we want to go through a list or a tuple element by element, we use a [for](https://www.learnpython.org/en/Loops) loop.\n", + "\n", + "With the for loop we can execute a set of statements, once for each item in a list or a tuple." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Parsons\n", + "Design\n", + "and\n", + "Technology\n" + ] + } + ], + "source": [ + "for term in terms: # term is just a placeholder indicating 'each element'\n", + " print(term)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Parsons!\n", + "Design!\n", + "and!\n", + "Technology!\n" + ] + } + ], + "source": [ + "# it can be any placeholder in replacement of 'term'\n", + "for a in terms:\n", + " # it will go through every 'a' in terms and execute something to that 'a'\n", + " print(a + '!') " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "you can loop/iterate through a tuple as well:" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Emma\n", + "Frank\n", + "Roy\n" + ] + } + ], + "source": [ + "people = ('Emma','Frank','Roy')\n", + "for person in people:\n", + " print(person)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "## Conversions among lists, tuples and strings\n", + "1. string method: split( )\n", + "1. string method: join( )\n", + "1. lisy( ) constructor\n", + "1. tuple( ) construct0r" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Curl', 'up', 'like', 'a', 'dead', 'leaf']\n" + ] + } + ], + "source": [ + "# string to list\n", + "str = \"Curl up like a dead leaf\"\n", + "str2li = str.split(' ') # split the string with a 'space' operator\n", + "print(str2li)" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Curl up like a dead leaf\n" + ] + } + ], + "source": [ + "# list to string\n", + "li2str = ' '.join(str2li) # join the list elements with a 'space' operator\n", + "print(li2str)" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "('Curl', 'up', 'like', 'a', 'dead', 'leaf')\n", + "['Curl', 'up', 'like', 'a', 'dead', 'leaf']\n" + ] + } + ], + "source": [ + "# list to tuple to list\n", + "li2tup = tuple(str2li)\n", + "print(li2tup)\n", + "tup2lis = list(li2tup)\n", + "print(tup2lis)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "
\n", + "\n", + "## Modifying elements with lists\n", + "\n", + "When you know at some point this collection of data will need to change, you should declare it as lists.\n", + "\n", + "but if you can always turn tuples into lists if you need to change elements.\n", + "\n", + "With lists, there are many things we can do that you can do with tuples:\n", + "\n", + "- Add elements\n", + "- Remove elements\n", + "- Insert element at a specific location\n", + "- Check index number\n", + "- Extend one list from another list\n", + "- Sorting\n", + "- element Count \n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Add elements\n", + "append( ) method adds the parameter to the end of your list" + ] + }, + { + "cell_type": "code", + "execution_count": 97, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Emma', 'Peter', 'Frank', 'Sven', 3, 'Judy']\n" + ] + } + ], + "source": [ + "names = [\"Emma\",\"Peter\",\"Frank\",\"Sven\"]\n", + "names.append(3) # append a number\n", + "names.append(\"Judy\") # append another string\n", + "print(names)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Remove elements\n", + "remove( ) deletes the element that matches specific value\n", + "\n", + "pop( ) deletes the element that matches the index position" + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Emma', 'Peter', 'Frank', 'Sven', 3, 'Judy']\n", + "['Emma', 'Peter', 'Frank', 'Sven', 'Judy']\n" + ] + } + ], + "source": [ + "print(names)\n", + "names.remove(3) # remove the element that matches 3\n", + "print(names)" + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Emma', 'Peter', 'Frank', 'Sven', 'Judy']\n", + "['Peter', 'Frank', 'Sven', 'Judy']\n" + ] + } + ], + "source": [ + "print(names)\n", + "names.pop(0) # remove the first element – 'Emma' from the list\n", + "print(names)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Insert Elements \n", + "inserts( ) takes two parameters: the index location and element value" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Emma', 'Bob', 'Peter', 'Frank', 'Sven', 'Judy']\n" + ] + } + ], + "source": [ + "names.insert(1,\"Bob\") # insert string at the second element position\n", + "print(names)" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 94, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# check the index number of specific value\n", + "names.index(\"Bob\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Extend lists\n", + "\n", + "Appending one list to another" + ] + }, + { + "cell_type": "code", + "execution_count": 96, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 0, 0, 0, 10, 1, 0]\n" + ] + } + ], + "source": [ + "list1 = [0,0,0,10,1,0]\n", + "list2 = [2]\n", + "list2.extend(list1)\n", + "print(list2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\n", + "### Sorting\n", + "order the list, reverse the order of the list\n", + "\n", + "sort( ) method sorts the list ascending by default.\n", + "\n", + "reverse( ) reverse the order of the list." + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 3, 9]\n" + ] + } + ], + "source": [ + "numbers = [9,0,3,2]\n", + "numbers.sort()\n", + "print(numbers)" + ] + }, + { + "cell_type": "code", + "execution_count": 111, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['apple', 'banana', 'watermelon']\n" + ] + } + ], + "source": [ + "fruits = [\"banana\",\"apple\",\"watermelon\"]\n", + "fruits.sort()\n", + "print(fruits)" + ] + }, + { + "cell_type": "code", + "execution_count": 112, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[9, 3, 2, 0]\n" + ] + } + ], + "source": [ + "numbers.reverse()\n", + "print(numbers)" + ] + }, + { + "cell_type": "code", + "execution_count": 113, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['watermelon', 'banana', 'apple']\n" + ] + } + ], + "source": [ + "fruits.reverse()\n", + "print(fruits)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "### Count\n", + "Lists have built-in function that allows you count the number of times one element appear in your list" + ] + }, + { + "cell_type": "code", + "execution_count": 114, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 114, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "words = ['flower','bee','bee','flower','leaf','bee']\n", + "words.count('bee')" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/.DS_Store b/Week_03/class_code/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/Week_03/class_code/.DS_Store differ diff --git a/Week_03/class_code/.ipynb_checkpoints/double_vs_single_quotes-checkpoint.ipynb b/Week_03/class_code/.ipynb_checkpoints/double_vs_single_quotes-checkpoint.ipynb new file mode 100644 index 0000000..b2ab00e --- /dev/null +++ b/Week_03/class_code/.ipynb_checkpoints/double_vs_single_quotes-checkpoint.ipynb @@ -0,0 +1,39 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Single quotes, double quotes." + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb b/Week_03/class_code/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb new file mode 100644 index 0000000..343588b --- /dev/null +++ b/Week_03/class_code/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb @@ -0,0 +1,667 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Get the 'lexical richness' of a piece of text\n", + "\n", + "We're going to write a function that accepts any input text. It will return to us a \"lexical richness score\" for that text.\n", + "\n", + "In the process, we're going to see the following in use:\n", + "\n", + "- Strings\n", + "- String methods\n", + "- Lists\n", + "- List methods\n", + "- Mathematical operations\n", + "- Functions" + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": {}, + "outputs": [], + "source": [ + "# Store string data in a variable called 'text'.\n", + "# (This string is from 'Doorway to Distruction,'\n", + "# a randomly chosen book from the Gutenberg Library of ebooks).\n", + "\n", + "text = \"\"\"\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Print the text.\n", + "\n", + "print(text)" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists. a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand.\n", + "\n", + "\"don't be a complete fool, vance!\" he said harshly. \"that machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Lowercase all text.\n", + "\n", + "text_lower = text.lower()\n", + "print(text_lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand\n", + "\n", + "don't be a complete fool vance he said harshly that machine can't\n", + "bring you anything but trouble\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room\n", + "\n" + ] + } + ], + "source": [ + "# Remove all unnecessary punctuation.\n", + "# Note that there are better ways to do this that we haven't yet learned.\n", + "\n", + "text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + "print(text_clean)" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['old', 'kelvin', 'martin', 'strained', 'futilely', 'against', 'the', 'rope', 'that', 'held', 'immovable', 'his', 'thin', 'wrists', 'a', 'crimsoned', 'bruise', 'raced', 'across', 'his', 'forehead', 'where', 'vance', 'had', 'slugged', 'him', 'with', 'a', 'heavy', 'hand', \"don't\", 'be', 'a', 'complete', 'fool', 'vance', 'he', 'said', 'harshly', 'that', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble', 'the', \"scientist's\", 'burly', 'assistant', 'glanced', 'wearily', 'up', 'from', 'where', 'he', 'coupled', 'heavy', 'batteries', 'in', 'series', 'at', 'the', 'rear', 'of', 'the', 'glittering', 'machine', 'that', 'entirely', 'filled', 'one', 'corner', 'of', 'the', 'windowless', 'room']\n" + ] + } + ], + "source": [ + "# Split the text into a list of words separated by whitespace.\n", + "\n", + "text_data = text_clean.split()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'a', 'a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'he', 'heavy', 'heavy', 'held', 'him', 'his', 'his', 'immovable', 'in', 'kelvin', 'machine', 'machine', 'martin', 'of', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'thin', 'trouble', 'up', 'vance', 'vance', 'wearily', 'where', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Sort the list alphabetically.\n", + "\n", + "text_data.sort()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "78\n" + ] + } + ], + "source": [ + "# Count the total number of words.\n", + "\n", + "num_words = len(text_data)\n", + "print(num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 69, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'heavy', 'held', 'him', 'his', 'immovable', 'in', 'kelvin', 'machine', 'martin', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'the', 'thin', 'trouble', 'up', 'vance', 'wearily', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Let's make a unique list of words.\n", + "# I.e. every word in the text is including in this list\n", + "# exactly once.\n", + "\n", + "unique_words = []\n", + "\n", + "for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + "\n", + "print(unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "63\n" + ] + } + ], + "source": [ + "# Let's count the number of unique words.\n", + "\n", + "num_unique_words = len(unique_words)\n", + "print(num_unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.8076923076923077" + ] + }, + "execution_count": 75, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This is enough information for a decent\n", + "# measure of lexical \"richness\".\n", + "\n", + "num_unique_words / num_words" + ] + }, + { + "cell_type": "code", + "execution_count": 82, + "metadata": {}, + "outputs": [], + "source": [ + "# Let's make all of this into a function.\n", + "\n", + "def printLexicalRichness(text):\n", + " # Lowercase the text\n", + " text_lower = text.lower()\n", + " # Clean unnecessary punctuation\n", + " text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + " # Split text into list\n", + " text_data = text_clean.split()\n", + " # Get the total words in the list\n", + " num_words = len(text_data)\n", + " # Make a separate unique list\n", + " unique_words = []\n", + " for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + " # Get the number of unique words\n", + " num_unique_words = len(unique_words)\n", + " \n", + " # Print the stat.\n", + " print(num_unique_words / num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'printLexicalRichness' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mNameError\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 305\u001b[0m _Though my love's constant as the Sun._\"\"\"\n\u001b[1;32m 306\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 307\u001b[0;31m \u001b[0mprintLexicalRichness\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbook\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mNameError\u001b[0m: name 'printLexicalRichness' is not defined" + ] + } + ], + "source": [ + "# Rather than get the richness of just a couple lines,\n", + "# let's get the richness of a huge chunk of text.\n", + "\n", + "book = \"\"\"\n", + "Special Investigator Billy Neville was annoyed, and for more reasons\n", + "than one. He had just done a tedious year in the jungles of Venus\n", + "stamping out the gooroo racket and then, on his way home to a\n", + "well-deserved leave and rest, had been diverted to Mars for a swift\n", + "clean-up of the diamond-mine robbery ring. And now, when he again\n", + "thought he would be free for a while, he found himself shunted to\n", + "little Pallas, capital of the Asteroid Confederation. But clever,\n", + "patient Colonel Frawley, commandant of all the Interplanetary Police in\n", + "the belt, merely smiled indulgently while Neville blew off his steam.\n", + "\n", + "\"You say,\" said Neville, still ruffled, \"that there has been a growing\n", + "wave of blackmail and extortion all over the System, coupled with a\n", + "dozen or so instances of well-to-do, respectable persons disappearing\n", + "without a trace. And you say that that has been going on for a couple\n", + "of years and several hundred of our crack operatives have been working\n", + "on it, directed by the best brains of the force, and yet haven't got\n", + "anywhere. And that up to now there have been no such cases develop in\n", + "the asteroids. Well, what do you want _me_ for? What's the emergency?\"\n", + "\n", + "The colonel laughed and dropped the ash from his cigar, preparatory to\n", + "lying back in his chair and taking another long, soothing drag. The\n", + "office of the Chief Inspector of the A.C. division of the I.P. was not\n", + "only well equipped for the work it had to do, but for comfort.\n", + "\n", + "\"I am astonished,\" he remarked, \"to hear an experienced policeman\n", + "indulge in such loose talk. Who said anything about having had the\n", + "_best_ brains on the job? Or that no progress had been made? Or that\n", + "there was no emergency? Any bad crime situation is always an emergency,\n", + "no matter how long it lasts. Which is all the more reason why we have\n", + "to break it up, and quickly. I tell you, things are becoming very\n", + "serious. Lifelong partners in business are becoming suspicious and\n", + "secretive toward each other; husbands and wives are getting jittery and\n", + "jealous. Nobody knows whom to trust. The most sacred confidences have a\n", + "way of leaking out. Then they are in the market for the highest bidder.\n", + "No boy, this thing is a headache. I never had a worse.\"\n", + "\n", + "\"All right, all right,\" growled Neville, resignedly. \"I'm stuck. Shoot!\n", + "How did it begin, and what do you know?\"\n", + "\n", + " * * * * *\n", + "\n", + "The colonel reached into a drawer and pulled out a fat jacket bulging\n", + "with papers, photostats, and interdepartmental reports.\n", + "\n", + "\"It began,\" he said, \"about two years ago, on Io and Callisto. It\n", + "spread all over the Jovian System and soured Ganymede and Europa.\n", + "The symptoms were first the disappearances of several prominent\n", + "citizens, followed by a wave of bankruptcies and suicides on both\n", + "planetoids. Nobody complained to the police. Then a squad of our\n", + "New York men picked up a petty chiseler who was trying to gouge the\n", + "Jovian Corporation's Tellurian office out of a large sum of money on\n", + "the strength of some damaging documents he possessed relating to a\n", + "hidden scandal in the life of the New York manager. From that lead,\n", + "they picked up a half-dozen other small fry extortionists and even\n", + "managed to grab their higher-up--a sort of middleman who specialized\n", + "in exploiting secret commercial information and scandalous material\n", + "about individuals. There the trail stopped. They put him through the\n", + "mill, but all he would say is that a man approached him with the\n", + "portfolio, sold him on its value for extortion purposes, and collected\n", + "in advance. There could be no follow up for the reason that after the\n", + "first transaction what profits the local gang could make out of the\n", + "dirty work would be their own.\"\n", + "\n", + "\"Yes,\" said Neville, \"I know the racket. When they handle it that way\n", + "it's hard to beat. You get any amount of minnows, but the whales get\n", + "away.\"\n", + "\n", + "\"Right. The disturbing thing about the contents of the portfolio was\n", + "the immense variety of secrets it contained and that it was evidently\n", + "prepared by one man. There were, for example, secret industrial\n", + "formulas evidently stolen for sale to a competitor. The bulk of it was\n", + "other commercial items, such as secret credit reports, business volume,\n", + "and the like. But there was a good deal of rather nasty personal stuff,\n", + "too. It was a gold mine of information for an unscrupulous blackmailer,\n", + "and every bit of it originated on Callisto. Now, whom do you think,\n", + "could have been in a position to compile it?\"\n", + "\n", + "\"The biggest corporation lawyer there, I should guess,\" said Neville.\n", + "\"Priests and doctors know a lot of personal secrets, but a good lawyer\n", + "manages to learn most everything.\"\n", + "\n", + "\"Right. Very right. We sent men to Callisto and learned that some\n", + "months earlier the most prominent lawyer of the place had announced one\n", + "day he must go over to Io to arrange some contracts. He went to Io,\n", + "all right, but was never seen again after he stepped out of the ship.\n", + "It was shortly after, that the wave of Callistan suicides and business\n", + "failures took place.\"\n", + "\n", + "\"All right,\" agreed Neville, \"so what? It has happened before. Even the\n", + "big ones go wrong now and then.\"\n", + "\n", + "\"Yes, but wait. That fellow had nothing to go wrong about. He was\n", + "tremendously successful, rich, happily married, and highly respected\n", + "for his outstanding integrity. Yet he could hardly have been kidnaped,\n", + "as there has never been a ransom demand. Nor has there ever been such a\n", + "demand in any of the other cases similar to it.\n", + "\n", + "\"The next case to be partially explained was that of the disappearance\n", + "of the president of the Jupiter Trust Company at Ionopolis. All the\n", + "most vital secrets of that bank turned up later in all parts of the\n", + "civilized system. We nabbed some peddlers, but it was the same story\n", + "as with the first gang. The facts are all here in this jacket. After a\n", + "little you can read the whole thing in detail.\"\n", + "\n", + "\"Uh, huh,\" grunted Neville, \"I'm beginning to see. But why _me_, and\n", + "why at Pallas?\"\n", + "\n", + "\"Because you've never worked in the asteroids and are not known here\n", + "to any but the higher officers. Among other secrets this ring has, are\n", + "a number of police secrets. That is why setting traps for them is so\n", + "difficult. I haven't told you that one of their victims seems to have\n", + "been one of us. That was Jack Sarkins, who was district commander at\n", + "Patroclus. He received an apparently genuine ethergram one day--and it\n", + "was in our most secret code--telling him to report to Mars at once.\n", + "He went off, alone, in his police rocket. He never got there. As to\n", + "Pallas, the reason you are here is because the place so far is clean.\n", + "Their system is to work a place just once and never come back. They\n", + "milk it dry the first time and there is no need to. Since we have no\n", + "luck tracing them after the crime, we are going to try a plant and wait\n", + "for the crime to come to it. You are the plant.\"\n", + "\n", + "\"I see,\" said Neville slowly. He was interested, but not enthusiastic.\n", + "\"Some day, somehow, someone is coming here and in some manner\n", + "force someone to yield up all the local dirt and then arrange his\n", + "disappearance. My role is to break it up before it happens. Sweet!\"\n", + "\n", + "\"You have such a way of putting things, Neville,\" chuckled the colonel,\n", + "\"but you do get the point.\"\n", + "\n", + "He rose and pushed the heavy folder toward his new aide.\n", + "\n", + "\"Bone this the rest of the afternoon. I'll be back.\"\n", + "\n", + " * * * * *\n", + "\n", + "It was quite late when Colonel Frawley returned and asked Neville\n", + "cheerily how he was getting on.\n", + "\n", + "\"I have the history,\" Neville answered, slamming the folder shut, \"and\n", + "a glimmering of what you are shooting at. This guy Simeon Carstairs, I\n", + "take it, is the local man you have picked as the most likely prospect\n", + "for your Master Mind crook to work on?\"\n", + "\n", + "\"He is. He is perfect bait. He is the sole owner of the Radiation\n", + "Extraction Company which has a secret process that Tellurian Radiant\n", + "Corporation has made a standing offer of five millions for. He controls\n", + "the local bank and often sits as magistrate. In addition, he has\n", + "substantial interests in Vesta and Juno industries. He probably knows\n", + "more about the asteroids and the people on them than any other living\n", + "man. Moreover, his present wife is a woman with an unhappy past and who\n", + "happens also to be related to an extremely wealthy Argentine family.\n", + "Any ring of extortionists who could worm old Simeon's secrets out of\n", + "him could write their own ticket.\"\n", + "\n", + "\"So I am to be a sort of private shadow.\"\n", + "\n", + "\"Not a bit of it. _I_ am his bodyguard. We are close friends and lately\n", + "I have made it a rule to be with him part of the time every day. No,\n", + "your role is that of observer from the sidelines. I shall introduce\n", + "you as the traveling representative of the London uniform house that\n", + "has the police contract. That will explain your presence here and your\n", + "occasional calls at headquarters. You might sell a few suits of clothes\n", + "on the side, or at least solicit them. Work that out for yourself.\"\n", + "\n", + "Neville grimaced. He was not fond of plainclothes work.\n", + "\n", + "\"But come, fellow. You've worked hard enough for one day. Go up to\n", + "my room and get into cits. Then I'll take you over to the town and\n", + "introduce you around. After that we'll go to a show. The showboat\n", + "landed about an hour ago.\"\n", + "\n", + "\"Showboat? What the hell is a showboat?\"\n", + "\n", + "\"I forget,\" said the colonel, \"that your work has been mostly on the\n", + "heavy planets where they have plenty of good playhouses in the cities.\n", + "Out here among these little rocks the diversions are brought around\n", + "periodically and peddled for the night. The showboat, my boy, is a\n", + "floating theater--a space ship with a stage and an auditorium in it, a\n", + "troupe of good actors and a cracking fine chorus. This one has been\n", + "making the rounds quite a while, though it never stopped here before\n", + "until last year. They say the show this year is even better. It is the\n", + "\"Lunar Follies of 2326,\" featuring a chorus of two hundred androids\n", + "and with Lilly Fitzpatrick and Lionel Dustan in the lead. Tonight, for\n", + "a change, you can relax and enjoy yourself. We can get down to brass\n", + "tacks tomorrow.\"\n", + "\n", + "\"Thanks, chief,\" said Neville, grinning from ear to ear. The\n", + "description of the showboat was music to his ears, for it had been\n", + "a long time since he had seen a good comedy and he felt the need of\n", + "relief from his sordid workaday life.\n", + "\n", + "\"When you're in your makeup,\" the colonel added, \"come on down and I'll\n", + "take you over in my copter.\"\n", + "\n", + " * * * * *\n", + "\n", + "It did not take Billy Neville long to make his transformation to the\n", + "personality of a clothing drummer. Every special cop had to be an\n", + "expert at the art of quick shifts of disguise and Neville was rather\n", + "better than most. Nor did it take long for the little blue copter to\n", + "whisk them halfway around the knobby little planetoid of Pallas. It\n", + "eased itself through an airlock into a doomed town, and there the\n", + "colonel left it with his orderly.\n", + "\n", + "The town itself possessed little interest for Neville though his\n", + "trained photographic eye missed few of its details. It was much like\n", + "the smaller doomed settlements on the Moon. He was more interested\n", + "in meeting the local magnate, whom they found in his office in the\n", + "Carstairs Building. The colonel made the introductions, during which\n", + "Neville sized up the man. He was of fair height, stockily built, and\n", + "had remarkably frank and friendly eyes for a self-made man of the\n", + "asteroids. Not that there was not a certain hardness about him and a\n", + "considerable degree of shrewdness, but he lacked the cynical cunning\n", + "so often displayed by the pioneers of the outer system. Neville noted\n", + "other details as well--the beginning of a set of triple chins, a little\n", + "brown mole with three hairs on it alongside his nose, and the way a\n", + "stray lock of hair kept falling over his left eye.\n", + "\n", + "\"Let's go,\" said the colonel, as soon as the formalities were over.\n", + "\n", + "Neville had to borrow a breathing helmet from Mr. Carstairs, for he had\n", + "not one of his own and they had to walk from the far portal of the dome\n", + "across the field to where the showboat lay parked. He thought wryly,\n", + "as he put it on, that he went from one extreme to another--from Venus,\n", + "where the air was over-moist, heavy and oppressive from its stagnation,\n", + "to windy, blustery Mars, and then here, where there was no air at all.\n", + "\n", + "As they approached the grounded ship they saw it was all lit up and\n", + "throngs of people were approaching from all sides. Flood lamps threw\n", + "great letters on the side of the silvery hull reading, \"Greatest Show\n", + "of the Void--Come One, Come All--Your Money Back if Not Absolutely\n", + "Satisfied.\" They went ahead of the queue, thanks to the prestige of\n", + "the colonel and the local tycoon, and were instantly admitted. It took\n", + "but a moment to check their breathers at the helmet room and then the\n", + "ushers had them in tow.\n", + "\n", + "\"See you after the show, Mr. Allington,\" said the colonel to Neville,\n", + "\"I will be in Mr. Carstairs box.\"\n", + "\n", + " * * * * *\n", + "\n", + "Neville sank into a seat and watched them go. Then he began to take\n", + "stock of the playhouse. The seats were comfortable and commodious,\n", + "evidently having been designed to hold patrons clad in heavy-dust\n", + "space-suits. The auditorium was almost circular, one semi-circle being\n", + "taken up by the stage, the other by the tiers of seats. Overhead ranged\n", + "a row of boxes jutting out above the spectators below. Neville puzzled\n", + "for a long time over the curtain that shut off the stage. It seemed\n", + "very unreal, like the shimmer of the aurora, but it affected vision to\n", + "the extent that the beholder could not say with any certainty _what_\n", + "was behind it. It was like looking through a waterfall. Then there was\n", + "eerie music, too, from an unseen source, flooding the air with queer\n", + "melodies. People continued to pour in. The house gradually darkened and\n", + "as it did the volume and wildness of the music rose. Then there was a\n", + "deep bong, and lights went completely out for a full second. The show\n", + "was on.\n", + "\n", + "Neville sat back and enjoyed it. He could not have done otherwise,\n", + "for the sign on the hull had not been an empty plug. It was the best\n", + "show in the void--or anywhere else, for that matter. A spectral voice\n", + "that seemed to come from everywhere in the house announced the first\n", + "number--The Dance of the Wood-sprites of Venus. Instantly little\n", + "flickers of light appeared throughout the house--a mass of vari-colored\n", + "fireflies blinking off and on and swirling in dizzy spirals. They\n", + "steadied and grew, coalesced into blobs of living fire--ruby, dazzling\n", + "green, ethereal blue and yellow. They swelled and shrank, took on\n", + "human forms only to abandon them; purple serpentine figures writhed\n", + "among them, paling to silvery smoke and then expiring as a shower of\n", + "violet sparks. And throughout was the steady, maddening rhythm of the\n", + "dance tune, unutterably savage and haunting--a folk dance of the hill\n", + "tribes of Venus. At last, when the sheer beauty of it began to lull\n", + "the viewers into a hypnotic trance, there came the shrill blare of\n", + "massed trumpets and the throb of mighty tom-toms culminating in an\n", + "ear-shattering discord that broke the spell.\n", + "\n", + "The lights were on. The stage was bare. Neville sat up straighter and\n", + "looked, blinking. It was as if he were in an abandoned warehouse. And\n", + "then the scenery began to grow. Yes, grow. Almost imperceptible it was,\n", + "at first, then more distinct. Nebulous bodies appeared, wisps of smoke.\n", + "They wavered, took on shape, took on color, took on the appearance of\n", + "solidity. The scent began to have meaning. Part of the background was a\n", + "gray cliff undercut with a yawning cave. It was a scene from the Moon,\n", + "a hangout of the cliffdwellers, those refugees from civilization who\n", + "chose to live the wild life of the undomed Moon rather than submit to\n", + "the demands of a more ordered life.\n", + "\n", + "Characters came on. There was a little drama, well conceived and well\n", + "acted. When it was over, the scene vanished as it had come. A comedy\n", + "team came out next and this time the appropriate scenery materialized\n", + "at once as one of them stumbled over an imaginary log and fell on his\n", + "face. The log was not there when he tripped, but it was there by the\n", + "time his nose hit the stage, neatly turning the joke on his companion\n", + "who had started to laugh at his unreasonable fall.\n", + "\n", + "On the show went, one scene swiftly succeeding the next. A song that\n", + "took the fancy of the crowd was a plaintive ballad. It ran:\n", + "\n", + " _They tell me you did not treat me right,_\n", + " _Nor are grateful for all I've done._\n", + " _I fear you're fickle as a meteorite_\n", + " _Though my love's constant as the Sun._\"\"\"\n", + "\n", + "printLexicalRichness(book)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Going further\n", + "\n", + "- What other stats can you get?\n", + " - longest word?\n", + " - shortest word?\n", + " - most frequent word?\n", + "- For the super adventurers\n", + " - check out nltk, we'll cover this more later, but you can get a head start" + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/.ipynb_checkpoints/palindrome_empty-checkpoint.ipynb b/Week_03/class_code/.ipynb_checkpoints/palindrome_empty-checkpoint.ipynb new file mode 100644 index 0000000..eb4f7a3 --- /dev/null +++ b/Week_03/class_code/.ipynb_checkpoints/palindrome_empty-checkpoint.ipynb @@ -0,0 +1,79 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Palindrome - live code\n", + "\n", + "\n", + "## What is a palindrome?\n", + "A palindrome is a word or phrase that is spelled the same forwards as backwards, like:\n", + "\n", + "```wow\n", + "Anna\n", + "race car\n", + "Was it a cat I saw?\n", + "```\n", + "\n", + "
\n", + "\n", + "## What will we make?\n", + "We are going to create a function that checks whether or not a given phrase is a palindrome. Here are our guidelines:\n", + "* Our function will be called `isPalindrome()`.\n", + "* It will accept one **argument** called `txt`, which is a string.\n", + "* It will **return** either True (if `txt` is a palindrome) or `False` (if `txt`\n", + " is not a palindrome).\n", + " \n", + "
\n", + "\n", + "## How will we test it along the way?\n", + "We will use the following test cases to check our function:\n", + "\n", + "The following should all return `True`:\n", + "```\n", + "isPalindrome('wow')\n", + "isPalindrome('12a3a21')\n", + "isPalindrome('Anna')\n", + "isPalindrome('race car')\n", + "isPalindrome('Was it a cat I saw?')\n", + "```\n", + "\n", + "The following should all return `False`:\n", + "```\n", + "isPalindrome('wowza')\n", + "isPalindrome('123a21')\n", + "isPalindrome('<3 mom <3')\n", + "```" + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/README.md b/Week_03/class_code/README.md new file mode 100644 index 0000000..da24755 --- /dev/null +++ b/Week_03/class_code/README.md @@ -0,0 +1 @@ +# This week's live code examples, shown in class. diff --git a/Week_03/class_code/[in_class]madlibs_invitation.ipynb b/Week_03/class_code/[in_class]madlibs_invitation.ipynb new file mode 100644 index 0000000..4736c19 --- /dev/null +++ b/Week_03/class_code/[in_class]madlibs_invitation.ipynb @@ -0,0 +1,327 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A Mad-Libs invitation generator\n", + "\n", + "Mad-Libs is a phrasal template word game where one player prompts others for a list of words to substitute for blanks in a story.\n", + "\n", + "We are going to create an event `invitation function` that would allow us to automate creating copies of event invitations.\n", + "\n", + "The invitation template:\n", + "```\n", + " Hey, _guestname_!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + " \n", + " Best,\n", + " Party bear\n", + " \n", + "```\n", + "\n", + "An example output:\n", + "```\n", + " Hey, Sven!\n", + " You are invited to a gathering! Join us on July 2nd at Union Square!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Break down components and structure of an invitation\n", + "1. Print out a small part of the invitation with variables\n", + "1. Curate versions for guests in guestlist\n", + "1. Declare event details as variables and assign values to them\n", + "1. Automate parts of the flow\n", + "1. Compile and make one big function to populate our invitations" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hey, Lan and Anna!\n" + ] + } + ], + "source": [ + "# Let's print out the invitation template first\n", + "\n", + "string_template = '''\n", + " Hey, %s!\n", + " You are invited to a %s! Join us on %s at %s!\n", + " Bring %s.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "'''\n", + "\n", + "name = \"Lan\"\n", + "name2 = \"Anna\"\n", + "\n", + "# the old way to print multiple variables together\n", + "print(\"Hey, \" + name + ' and '+ name2 + '!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## String formatting\n", + "\n", + "- %d \n", + "- %s\n", + "- %f\n", + "\n", + "print( ) supports formatting of console output that is rudimentary at best. You can choose how to separate printed objects, and you can specify what goes at the end of the printed line. That’s about it.\n", + "\n", + "In many cases, you’ll need more `precise control` over the appearance of data destined for display. Python provides several ways to format output string data.\n", + "\n", + "- [string_formatting_modulo](https://realpython.com/python-input-output/#the-string-modulo-operator)\n", + "- [newer_ways_of_string_formatting](https://realpython.com/python-formatted-output/)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + " Hey, Lan and Anna!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n" + ] + } + ], + "source": [ + "# Create our invitation template using string formatting\n", + "# Test out string formatting with only one parameter variable\n", + "\n", + "print(string_template % (name,name2))" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + " Hey, Lan!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Anna!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Jason!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Sven and friends!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n" + ] + } + ], + "source": [ + "# Create our guestlist and event variables using lists and tuples\n", + "guestlist = ['Lan','Anna','Jason','Sven and friends']\n", + "\n", + "# This is a for loop that iterates through all elements of a list\n", + "# for var in list\n", + "# guest is just a variable name – representing every element in a list\n", + "for guest in guestlist:\n", + " print(string_template % (guest))" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [], + "source": [ + "# Create functions that will automate some parts of the process\n", + "import random\n", + "event_type = 'gathering'\n", + "date = 'July 20th'\n", + "location = 'Union Square'\n", + "items = ['an umbrella','a wok','a water bottle','masks','signs','games']\n", + "\n", + "\n", + "# Compiling into one function that takes the following inputs\n", + "def createInvitations(guestlist,event_type,date,location,items):\n", + " \n", + " # This function will converts a list of items into a string of 'a, b, c, and d.'\n", + " def allItems(li):\n", + " return ', '.join(li[:-1]) + ', and %s' % (li[-1])\n", + " \n", + " # This function will outputs a random item from a list input\n", + " def randItem(li):\n", + " return random.choice(li)\n", + "\n", + " for guest in guestlist:\n", + " # variables within the tuple are from the function input\n", + " print(string_template % (guest, \n", + " event_type, \n", + " date,\n", + " location,\n", + " # call allItem function\n", + " # try randItem(items) instead\n", + " allItems(items) \n", + " ))" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + " Hey, Lan!\n", + " You are invited to a gathering! Join us on July 20th at Union Square!\n", + " Bring an umbrella, a wok, a water bottle, masks, signs, and games.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Anna!\n", + " You are invited to a gathering! Join us on July 20th at Union Square!\n", + " Bring an umbrella, a wok, a water bottle, masks, signs, and games.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Jason!\n", + " You are invited to a gathering! Join us on July 20th at Union Square!\n", + " Bring an umbrella, a wok, a water bottle, masks, signs, and games.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n", + "\n", + " Hey, Sven and friends!\n", + " You are invited to a gathering! Join us on July 20th at Union Square!\n", + " Bring an umbrella, a wok, a water bottle, masks, signs, and games.\n", + "\n", + " Best,\n", + " Party bear\n", + " \n", + " ---\n", + "\n" + ] + } + ], + "source": [ + "# Let's compile and populate!\n", + "createInvitations(guestlist,event_type,date,location,items)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Next steps\n", + "1. Check out [String Documentation](https://docs.python.org/2.5/lib/string-methods.html), [List Documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists), and [Tuple Documentation](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)\n", + "1. We have cheatsheets made for [strings, lists and tuples](https://github.com/parsons-python-summer-2020/python/tree/master/Week_03/cheatsheets)\n", + "1. \n", + "\n", + "\n", + "Some improvement you can make with this current code:\n", + "> 1. How to ask our guests to individually bring a random object from the list of items?\n", + "> 1. How to encrpyt some parts of our invitation using string methods?\n" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/double_vs_single_quotes.ipynb b/Week_03/class_code/double_vs_single_quotes.ipynb new file mode 100644 index 0000000..b2ab00e --- /dev/null +++ b/Week_03/class_code/double_vs_single_quotes.ipynb @@ -0,0 +1,39 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Single quotes, double quotes." + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/madlibs_event_invitation.ipynb b/Week_03/class_code/madlibs_event_invitation.ipynb new file mode 100644 index 0000000..2a26a2a --- /dev/null +++ b/Week_03/class_code/madlibs_event_invitation.ipynb @@ -0,0 +1,186 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A Mad-Libs invitation generator\n", + "\n", + "Mad-Libs is a phrasal template word game where one player prompts others for a list of words to substitute for blanks in a story.\n", + "\n", + "We are going to create an event `invitation function` that would allow us to automate creating copies of event invitations.\n", + "\n", + "The invitation template:\n", + "```\n", + " Hey,_guestname_!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + " \n", + " Best,\n", + " Party bear\n", + " \n", + "```\n", + "\n", + "An example output:\n", + "```\n", + " Hey, Sven!\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "def event(namelist, event_type, date, loc, items):\n", + " \"\"\"\n", + " This function takes event information input, parse them and turn them into\n", + " a formatted invitation that's ready to be duplicate and populate.\n", + " \"\"\"\n", + " # outputs a random item from the list\n", + " def getRand(list):\n", + " return random.choice(list)\n", + " \n", + " # formats all outputs form a list as 'a, b, and c'\n", + " def getAll(li):\n", + " return ', '.join(li[:-1]) + \", and %s\" %(li[-1])\n", + " \n", + " \n", + " # variables needed:\n", + " guestlist = namelist\n", + " type_of_event = event_type\n", + " date = date[::-1]\n", + " location = loc[::-1] # a simple reversed encrption\n", + " items = items\n", + " invite_template = '''\n", + " Hey %s:\n", + " You are invited to a %s! Join us on %s at %s!\n", + " Bring %s.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " ''' \n", + " \n", + " # loop through all guest tuples in the guestlist\n", + " # populate our invitations\n", + " for guests in guestlist:\n", + " print(invite_template % (guests,\n", + " type_of_event,\n", + " date,\n", + " location,\n", + " getAll(items)# try getRand()\n", + " ))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + " Hey Bob:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n", + "\n", + " Hey Mary & Friends:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n", + "\n", + " Hey Lan:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n", + "\n", + " Hey Anna:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n", + "\n", + " Hey Sven and friends:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n", + "\n", + " Hey Jason:\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "\n", + " ---\n", + " \n" + ] + } + ], + "source": [ + "guests = (\"Bob\",\"Mary & Friends\",\"Lan\",\"Anna\",\"Sven and friends\",\"Jason\")\n", + "items = ['beverages','games','signs',\"masks\",\"facecovers\"]\n", + "\n", + "# call the generator function to populate invitations:\n", + "event(guests, \"gathering\", \"July 2nd\", \"Union Square\", items)" + ] + } + ], + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/madlibs_event_invitation_empty.ipynb b/Week_03/class_code/madlibs_event_invitation_empty.ipynb new file mode 100644 index 0000000..f4d79c2 --- /dev/null +++ b/Week_03/class_code/madlibs_event_invitation_empty.ipynb @@ -0,0 +1,112 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A Mad-Libs invitation generator\n", + "\n", + "Mad-Libs is a phrasal template word game where one player prompts others for a list of words to substitute for blanks in a story.\n", + "\n", + "We are going to create an event `invitation function` that would allow us to automate creating copies of event invitations.\n", + "\n", + "The invitation template:\n", + "```\n", + " Hey, _guestname_!\n", + " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", + " Bring _items_.\n", + " \n", + " Best,\n", + " Party bear\n", + " \n", + "```\n", + "\n", + "An example output:\n", + "```\n", + " Hey, Sven!\n", + " You are invited to a gathering! Join us on dn2 yluJ at erauqS noinU!\n", + " Bring beverages, games, signs, masks, and facecovers.\n", + "\n", + " Best,\n", + " Party bear\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Break down components and structure of an invitation" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [], + "source": [ + "# let's print out the invitation template first" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": {}, + "outputs": [], + "source": [ + "# create our invitation template using string formatting\n", + "# test out string formatting with only one parameter variable" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": {}, + "outputs": [], + "source": [ + "# create our guestlist and event info using lists and tuples" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [], + "source": [ + "# create functions that will automate some process" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": {}, + "outputs": [], + "source": [ + "# let's populate" + ] + } + ], + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/class_code/palindrome_empty.ipynb b/Week_03/class_code/palindrome_empty.ipynb new file mode 100644 index 0000000..5239bc0 --- /dev/null +++ b/Week_03/class_code/palindrome_empty.ipynb @@ -0,0 +1,80 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Palindrome - live code\n", + "\n", + "\n", + "## What is a palindrome?\n", + "A palindrome is a word or phrase that is spelled the same forwards as backwards, like:\n", + "\n", + "```\n", + "wow\n", + "Anna\n", + "race car\n", + "Was it a cat I saw?\n", + "```\n", + "\n", + "## What will we make?\n", + "We are going to create a function that checks whether or not a given phrase is a palindrome. Here's the plan:\n", + "* Our function will be called `isPalindrome()`.\n", + "* It will accept one **argument** called `txt`, which is a string.\n", + "* It will print True if `txt` is a palindrome or `False` if `txt`\n", + " is not a palindrome.\n", + "\n", + "## How will we test our function along the way?\n", + "We will use the following test cases to guide us:\n", + "\n", + "The following should all return `True`:\n", + "```\n", + "isPalindrome('wow')\n", + "isPalindrome('12a3a21')\n", + "isPalindrome('Anna')\n", + "isPalindrome('race car')\n", + "isPalindrome('Was it a cat I saw?')\n", + "```\n", + "\n", + "The following should all return `False`:\n", + "```\n", + "isPalindrome('wowza')\n", + "isPalindrome('123a21')\n", + "isPalindrome('<3 mom <3')\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# wow --> wow\n", + "# Anna --> \n", + "# race car --> " + ] + } + ], + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/exercises/.DS_Store b/Week_03/exercises/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/Week_03/exercises/.DS_Store differ diff --git a/Week_03/exercises/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb b/Week_03/exercises/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb new file mode 100644 index 0000000..e165632 --- /dev/null +++ b/Week_03/exercises/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb @@ -0,0 +1,663 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Get the 'lexical richness' of a piece of text\n", + "\n", + "We're going to write a function that accepts any input text. It will return to us a \"lexical richness score\" for that text.\n", + "\n", + "In the process, we're going to see the following in use:\n", + "\n", + "- Strings\n", + "- String methods\n", + "- Lists\n", + "- List methods\n", + "- Mathematical operations\n", + "- Functions" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Store string data in a variable called 'text'.\n", + "# (This string is from 'Doorway to Distruction,'\n", + "# a randomly chosen book from the Gutenberg Library of ebooks).\n", + "\n", + "text = \"\"\"\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Print the text.\n", + "\n", + "print(text)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists. a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand.\n", + "\n", + "\"don't be a complete fool, vance!\" he said harshly. \"that machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Lowercase all text.\n", + "\n", + "text_lower = text.lower()\n", + "print(text_lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand\n", + "\n", + "don't be a complete fool vance he said harshly that machine can't\n", + "bring you anything but trouble\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room\n", + "\n" + ] + } + ], + "source": [ + "# Remove all unnecessary punctuation.\n", + "# Note that there are better ways to do this that we haven't yet learned.\n", + "\n", + "text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + "print(text_clean)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['old', 'kelvin', 'martin', 'strained', 'futilely', 'against', 'the', 'rope', 'that', 'held', 'immovable', 'his', 'thin', 'wrists', 'a', 'crimsoned', 'bruise', 'raced', 'across', 'his', 'forehead', 'where', 'vance', 'had', 'slugged', 'him', 'with', 'a', 'heavy', 'hand', \"don't\", 'be', 'a', 'complete', 'fool', 'vance', 'he', 'said', 'harshly', 'that', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble', 'the', \"scientist's\", 'burly', 'assistant', 'glanced', 'wearily', 'up', 'from', 'where', 'he', 'coupled', 'heavy', 'batteries', 'in', 'series', 'at', 'the', 'rear', 'of', 'the', 'glittering', 'machine', 'that', 'entirely', 'filled', 'one', 'corner', 'of', 'the', 'windowless', 'room']\n" + ] + } + ], + "source": [ + "# Split the text into a list of words separated by whitespace.\n", + "\n", + "text_data = text_clean.split()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'a', 'a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'he', 'heavy', 'heavy', 'held', 'him', 'his', 'his', 'immovable', 'in', 'kelvin', 'machine', 'machine', 'martin', 'of', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'thin', 'trouble', 'up', 'vance', 'vance', 'wearily', 'where', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Sort the list alphabetically.\n", + "\n", + "text_data.sort()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "78\n" + ] + } + ], + "source": [ + "# Count the total number of words.\n", + "\n", + "num_words = len(text_data)\n", + "print(num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'heavy', 'held', 'him', 'his', 'immovable', 'in', 'kelvin', 'machine', 'martin', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'the', 'thin', 'trouble', 'up', 'vance', 'wearily', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Let's make a unique list of words.\n", + "# I.e. every word in the text is including in this list\n", + "# exactly once.\n", + "\n", + "unique_words = []\n", + "\n", + "for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + "\n", + "print(unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "63\n" + ] + } + ], + "source": [ + "# Let's count the number of unique words.\n", + "\n", + "num_unique_words = len(unique_words)\n", + "print(num_unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.8076923076923077" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This is enough information for a decent\n", + "# measure of lexical \"richness\".\n", + "\n", + "num_unique_words / num_words" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Let's make all of this into a function.\n", + "\n", + "def printLexicalRichness(text):\n", + " # Lowercase the text\n", + " text_lower = text.lower()\n", + " # Clean unnecessary punctuation\n", + " text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + " # Split text into list\n", + " text_data = text_clean.split()\n", + " # Get the total words in the list\n", + " num_words = len(text_data)\n", + " # Make a separate unique list\n", + " unique_words = []\n", + " for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + " # Get the number of unique words\n", + " num_unique_words = len(unique_words)\n", + " \n", + " # Print the stat.\n", + " print(num_unique_words / num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.3717331499312242\n" + ] + } + ], + "source": [ + "# Rather than get the richness of just a couple lines,\n", + "# let's get the richness of a huge chunk of text.\n", + "\n", + "book = \"\"\"\n", + "Special Investigator Billy Neville was annoyed, and for more reasons\n", + "than one. He had just done a tedious year in the jungles of Venus\n", + "stamping out the gooroo racket and then, on his way home to a\n", + "well-deserved leave and rest, had been diverted to Mars for a swift\n", + "clean-up of the diamond-mine robbery ring. And now, when he again\n", + "thought he would be free for a while, he found himself shunted to\n", + "little Pallas, capital of the Asteroid Confederation. But clever,\n", + "patient Colonel Frawley, commandant of all the Interplanetary Police in\n", + "the belt, merely smiled indulgently while Neville blew off his steam.\n", + "\n", + "\"You say,\" said Neville, still ruffled, \"that there has been a growing\n", + "wave of blackmail and extortion all over the System, coupled with a\n", + "dozen or so instances of well-to-do, respectable persons disappearing\n", + "without a trace. And you say that that has been going on for a couple\n", + "of years and several hundred of our crack operatives have been working\n", + "on it, directed by the best brains of the force, and yet haven't got\n", + "anywhere. And that up to now there have been no such cases develop in\n", + "the asteroids. Well, what do you want _me_ for? What's the emergency?\"\n", + "\n", + "The colonel laughed and dropped the ash from his cigar, preparatory to\n", + "lying back in his chair and taking another long, soothing drag. The\n", + "office of the Chief Inspector of the A.C. division of the I.P. was not\n", + "only well equipped for the work it had to do, but for comfort.\n", + "\n", + "\"I am astonished,\" he remarked, \"to hear an experienced policeman\n", + "indulge in such loose talk. Who said anything about having had the\n", + "_best_ brains on the job? Or that no progress had been made? Or that\n", + "there was no emergency? Any bad crime situation is always an emergency,\n", + "no matter how long it lasts. Which is all the more reason why we have\n", + "to break it up, and quickly. I tell you, things are becoming very\n", + "serious. Lifelong partners in business are becoming suspicious and\n", + "secretive toward each other; husbands and wives are getting jittery and\n", + "jealous. Nobody knows whom to trust. The most sacred confidences have a\n", + "way of leaking out. Then they are in the market for the highest bidder.\n", + "No boy, this thing is a headache. I never had a worse.\"\n", + "\n", + "\"All right, all right,\" growled Neville, resignedly. \"I'm stuck. Shoot!\n", + "How did it begin, and what do you know?\"\n", + "\n", + " * * * * *\n", + "\n", + "The colonel reached into a drawer and pulled out a fat jacket bulging\n", + "with papers, photostats, and interdepartmental reports.\n", + "\n", + "\"It began,\" he said, \"about two years ago, on Io and Callisto. It\n", + "spread all over the Jovian System and soured Ganymede and Europa.\n", + "The symptoms were first the disappearances of several prominent\n", + "citizens, followed by a wave of bankruptcies and suicides on both\n", + "planetoids. Nobody complained to the police. Then a squad of our\n", + "New York men picked up a petty chiseler who was trying to gouge the\n", + "Jovian Corporation's Tellurian office out of a large sum of money on\n", + "the strength of some damaging documents he possessed relating to a\n", + "hidden scandal in the life of the New York manager. From that lead,\n", + "they picked up a half-dozen other small fry extortionists and even\n", + "managed to grab their higher-up--a sort of middleman who specialized\n", + "in exploiting secret commercial information and scandalous material\n", + "about individuals. There the trail stopped. They put him through the\n", + "mill, but all he would say is that a man approached him with the\n", + "portfolio, sold him on its value for extortion purposes, and collected\n", + "in advance. There could be no follow up for the reason that after the\n", + "first transaction what profits the local gang could make out of the\n", + "dirty work would be their own.\"\n", + "\n", + "\"Yes,\" said Neville, \"I know the racket. When they handle it that way\n", + "it's hard to beat. You get any amount of minnows, but the whales get\n", + "away.\"\n", + "\n", + "\"Right. The disturbing thing about the contents of the portfolio was\n", + "the immense variety of secrets it contained and that it was evidently\n", + "prepared by one man. There were, for example, secret industrial\n", + "formulas evidently stolen for sale to a competitor. The bulk of it was\n", + "other commercial items, such as secret credit reports, business volume,\n", + "and the like. But there was a good deal of rather nasty personal stuff,\n", + "too. It was a gold mine of information for an unscrupulous blackmailer,\n", + "and every bit of it originated on Callisto. Now, whom do you think,\n", + "could have been in a position to compile it?\"\n", + "\n", + "\"The biggest corporation lawyer there, I should guess,\" said Neville.\n", + "\"Priests and doctors know a lot of personal secrets, but a good lawyer\n", + "manages to learn most everything.\"\n", + "\n", + "\"Right. Very right. We sent men to Callisto and learned that some\n", + "months earlier the most prominent lawyer of the place had announced one\n", + "day he must go over to Io to arrange some contracts. He went to Io,\n", + "all right, but was never seen again after he stepped out of the ship.\n", + "It was shortly after, that the wave of Callistan suicides and business\n", + "failures took place.\"\n", + "\n", + "\"All right,\" agreed Neville, \"so what? It has happened before. Even the\n", + "big ones go wrong now and then.\"\n", + "\n", + "\"Yes, but wait. That fellow had nothing to go wrong about. He was\n", + "tremendously successful, rich, happily married, and highly respected\n", + "for his outstanding integrity. Yet he could hardly have been kidnaped,\n", + "as there has never been a ransom demand. Nor has there ever been such a\n", + "demand in any of the other cases similar to it.\n", + "\n", + "\"The next case to be partially explained was that of the disappearance\n", + "of the president of the Jupiter Trust Company at Ionopolis. All the\n", + "most vital secrets of that bank turned up later in all parts of the\n", + "civilized system. We nabbed some peddlers, but it was the same story\n", + "as with the first gang. The facts are all here in this jacket. After a\n", + "little you can read the whole thing in detail.\"\n", + "\n", + "\"Uh, huh,\" grunted Neville, \"I'm beginning to see. But why _me_, and\n", + "why at Pallas?\"\n", + "\n", + "\"Because you've never worked in the asteroids and are not known here\n", + "to any but the higher officers. Among other secrets this ring has, are\n", + "a number of police secrets. That is why setting traps for them is so\n", + "difficult. I haven't told you that one of their victims seems to have\n", + "been one of us. That was Jack Sarkins, who was district commander at\n", + "Patroclus. He received an apparently genuine ethergram one day--and it\n", + "was in our most secret code--telling him to report to Mars at once.\n", + "He went off, alone, in his police rocket. He never got there. As to\n", + "Pallas, the reason you are here is because the place so far is clean.\n", + "Their system is to work a place just once and never come back. They\n", + "milk it dry the first time and there is no need to. Since we have no\n", + "luck tracing them after the crime, we are going to try a plant and wait\n", + "for the crime to come to it. You are the plant.\"\n", + "\n", + "\"I see,\" said Neville slowly. He was interested, but not enthusiastic.\n", + "\"Some day, somehow, someone is coming here and in some manner\n", + "force someone to yield up all the local dirt and then arrange his\n", + "disappearance. My role is to break it up before it happens. Sweet!\"\n", + "\n", + "\"You have such a way of putting things, Neville,\" chuckled the colonel,\n", + "\"but you do get the point.\"\n", + "\n", + "He rose and pushed the heavy folder toward his new aide.\n", + "\n", + "\"Bone this the rest of the afternoon. I'll be back.\"\n", + "\n", + " * * * * *\n", + "\n", + "It was quite late when Colonel Frawley returned and asked Neville\n", + "cheerily how he was getting on.\n", + "\n", + "\"I have the history,\" Neville answered, slamming the folder shut, \"and\n", + "a glimmering of what you are shooting at. This guy Simeon Carstairs, I\n", + "take it, is the local man you have picked as the most likely prospect\n", + "for your Master Mind crook to work on?\"\n", + "\n", + "\"He is. He is perfect bait. He is the sole owner of the Radiation\n", + "Extraction Company which has a secret process that Tellurian Radiant\n", + "Corporation has made a standing offer of five millions for. He controls\n", + "the local bank and often sits as magistrate. In addition, he has\n", + "substantial interests in Vesta and Juno industries. He probably knows\n", + "more about the asteroids and the people on them than any other living\n", + "man. Moreover, his present wife is a woman with an unhappy past and who\n", + "happens also to be related to an extremely wealthy Argentine family.\n", + "Any ring of extortionists who could worm old Simeon's secrets out of\n", + "him could write their own ticket.\"\n", + "\n", + "\"So I am to be a sort of private shadow.\"\n", + "\n", + "\"Not a bit of it. _I_ am his bodyguard. We are close friends and lately\n", + "I have made it a rule to be with him part of the time every day. No,\n", + "your role is that of observer from the sidelines. I shall introduce\n", + "you as the traveling representative of the London uniform house that\n", + "has the police contract. That will explain your presence here and your\n", + "occasional calls at headquarters. You might sell a few suits of clothes\n", + "on the side, or at least solicit them. Work that out for yourself.\"\n", + "\n", + "Neville grimaced. He was not fond of plainclothes work.\n", + "\n", + "\"But come, fellow. You've worked hard enough for one day. Go up to\n", + "my room and get into cits. Then I'll take you over to the town and\n", + "introduce you around. After that we'll go to a show. The showboat\n", + "landed about an hour ago.\"\n", + "\n", + "\"Showboat? What the hell is a showboat?\"\n", + "\n", + "\"I forget,\" said the colonel, \"that your work has been mostly on the\n", + "heavy planets where they have plenty of good playhouses in the cities.\n", + "Out here among these little rocks the diversions are brought around\n", + "periodically and peddled for the night. The showboat, my boy, is a\n", + "floating theater--a space ship with a stage and an auditorium in it, a\n", + "troupe of good actors and a cracking fine chorus. This one has been\n", + "making the rounds quite a while, though it never stopped here before\n", + "until last year. They say the show this year is even better. It is the\n", + "\"Lunar Follies of 2326,\" featuring a chorus of two hundred androids\n", + "and with Lilly Fitzpatrick and Lionel Dustan in the lead. Tonight, for\n", + "a change, you can relax and enjoy yourself. We can get down to brass\n", + "tacks tomorrow.\"\n", + "\n", + "\"Thanks, chief,\" said Neville, grinning from ear to ear. The\n", + "description of the showboat was music to his ears, for it had been\n", + "a long time since he had seen a good comedy and he felt the need of\n", + "relief from his sordid workaday life.\n", + "\n", + "\"When you're in your makeup,\" the colonel added, \"come on down and I'll\n", + "take you over in my copter.\"\n", + "\n", + " * * * * *\n", + "\n", + "It did not take Billy Neville long to make his transformation to the\n", + "personality of a clothing drummer. Every special cop had to be an\n", + "expert at the art of quick shifts of disguise and Neville was rather\n", + "better than most. Nor did it take long for the little blue copter to\n", + "whisk them halfway around the knobby little planetoid of Pallas. It\n", + "eased itself through an airlock into a doomed town, and there the\n", + "colonel left it with his orderly.\n", + "\n", + "The town itself possessed little interest for Neville though his\n", + "trained photographic eye missed few of its details. It was much like\n", + "the smaller doomed settlements on the Moon. He was more interested\n", + "in meeting the local magnate, whom they found in his office in the\n", + "Carstairs Building. The colonel made the introductions, during which\n", + "Neville sized up the man. He was of fair height, stockily built, and\n", + "had remarkably frank and friendly eyes for a self-made man of the\n", + "asteroids. Not that there was not a certain hardness about him and a\n", + "considerable degree of shrewdness, but he lacked the cynical cunning\n", + "so often displayed by the pioneers of the outer system. Neville noted\n", + "other details as well--the beginning of a set of triple chins, a little\n", + "brown mole with three hairs on it alongside his nose, and the way a\n", + "stray lock of hair kept falling over his left eye.\n", + "\n", + "\"Let's go,\" said the colonel, as soon as the formalities were over.\n", + "\n", + "Neville had to borrow a breathing helmet from Mr. Carstairs, for he had\n", + "not one of his own and they had to walk from the far portal of the dome\n", + "across the field to where the showboat lay parked. He thought wryly,\n", + "as he put it on, that he went from one extreme to another--from Venus,\n", + "where the air was over-moist, heavy and oppressive from its stagnation,\n", + "to windy, blustery Mars, and then here, where there was no air at all.\n", + "\n", + "As they approached the grounded ship they saw it was all lit up and\n", + "throngs of people were approaching from all sides. Flood lamps threw\n", + "great letters on the side of the silvery hull reading, \"Greatest Show\n", + "of the Void--Come One, Come All--Your Money Back if Not Absolutely\n", + "Satisfied.\" They went ahead of the queue, thanks to the prestige of\n", + "the colonel and the local tycoon, and were instantly admitted. It took\n", + "but a moment to check their breathers at the helmet room and then the\n", + "ushers had them in tow.\n", + "\n", + "\"See you after the show, Mr. Allington,\" said the colonel to Neville,\n", + "\"I will be in Mr. Carstairs box.\"\n", + "\n", + " * * * * *\n", + "\n", + "Neville sank into a seat and watched them go. Then he began to take\n", + "stock of the playhouse. The seats were comfortable and commodious,\n", + "evidently having been designed to hold patrons clad in heavy-dust\n", + "space-suits. The auditorium was almost circular, one semi-circle being\n", + "taken up by the stage, the other by the tiers of seats. Overhead ranged\n", + "a row of boxes jutting out above the spectators below. Neville puzzled\n", + "for a long time over the curtain that shut off the stage. It seemed\n", + "very unreal, like the shimmer of the aurora, but it affected vision to\n", + "the extent that the beholder could not say with any certainty _what_\n", + "was behind it. It was like looking through a waterfall. Then there was\n", + "eerie music, too, from an unseen source, flooding the air with queer\n", + "melodies. People continued to pour in. The house gradually darkened and\n", + "as it did the volume and wildness of the music rose. Then there was a\n", + "deep bong, and lights went completely out for a full second. The show\n", + "was on.\n", + "\n", + "Neville sat back and enjoyed it. He could not have done otherwise,\n", + "for the sign on the hull had not been an empty plug. It was the best\n", + "show in the void--or anywhere else, for that matter. A spectral voice\n", + "that seemed to come from everywhere in the house announced the first\n", + "number--The Dance of the Wood-sprites of Venus. Instantly little\n", + "flickers of light appeared throughout the house--a mass of vari-colored\n", + "fireflies blinking off and on and swirling in dizzy spirals. They\n", + "steadied and grew, coalesced into blobs of living fire--ruby, dazzling\n", + "green, ethereal blue and yellow. They swelled and shrank, took on\n", + "human forms only to abandon them; purple serpentine figures writhed\n", + "among them, paling to silvery smoke and then expiring as a shower of\n", + "violet sparks. And throughout was the steady, maddening rhythm of the\n", + "dance tune, unutterably savage and haunting--a folk dance of the hill\n", + "tribes of Venus. At last, when the sheer beauty of it began to lull\n", + "the viewers into a hypnotic trance, there came the shrill blare of\n", + "massed trumpets and the throb of mighty tom-toms culminating in an\n", + "ear-shattering discord that broke the spell.\n", + "\n", + "The lights were on. The stage was bare. Neville sat up straighter and\n", + "looked, blinking. It was as if he were in an abandoned warehouse. And\n", + "then the scenery began to grow. Yes, grow. Almost imperceptible it was,\n", + "at first, then more distinct. Nebulous bodies appeared, wisps of smoke.\n", + "They wavered, took on shape, took on color, took on the appearance of\n", + "solidity. The scent began to have meaning. Part of the background was a\n", + "gray cliff undercut with a yawning cave. It was a scene from the Moon,\n", + "a hangout of the cliffdwellers, those refugees from civilization who\n", + "chose to live the wild life of the undomed Moon rather than submit to\n", + "the demands of a more ordered life.\n", + "\n", + "Characters came on. There was a little drama, well conceived and well\n", + "acted. When it was over, the scene vanished as it had come. A comedy\n", + "team came out next and this time the appropriate scenery materialized\n", + "at once as one of them stumbled over an imaginary log and fell on his\n", + "face. The log was not there when he tripped, but it was there by the\n", + "time his nose hit the stage, neatly turning the joke on his companion\n", + "who had started to laugh at his unreasonable fall.\n", + "\n", + "On the show went, one scene swiftly succeeding the next. A song that\n", + "took the fancy of the crowd was a plaintive ballad. It ran:\n", + "\n", + " _They tell me you did not treat me right,_\n", + " _Nor are grateful for all I've done._\n", + " _I fear you're fickle as a meteorite_\n", + " _Though my love's constant as the Sun._\"\"\"\n", + "\n", + "printLexicalRichness(book)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Going further\n", + "\n", + "- What other stats can you get?\n", + " - longest word?\n", + " - shortest word?\n", + " - most frequent word?\n", + "- For the super adventurers\n", + " - check out the `nltk` library, read it's documentation. Think about what it allows us to do better or differently. We'll cover this more later, but you can get a head start" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/exercises/.ipynb_checkpoints/palindrome_completed_code_and_going_further-checkpoint.ipynb b/Week_03/exercises/.ipynb_checkpoints/palindrome_completed_code_and_going_further-checkpoint.ipynb new file mode 100644 index 0000000..f3fbcdd --- /dev/null +++ b/Week_03/exercises/.ipynb_checkpoints/palindrome_completed_code_and_going_further-checkpoint.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Palindrome - completed code & going further\n", + "\n", + "## What is a palindrome?\n", + "A palindrome is a word or phrase that is spelled the same forwards as backwards, like `wow`. Capitalization, whitespace, and punctuation are often ignored, so examples like `Anna`, `race car`, and `Was it a cat I saw?` are also palindromes.\n", + "\n", + "
\n", + "\n", + "## What are we going to make?\n", + "We are going to create a function that checks whether or not a given phrase is a palindrome. Here are our guidelines:\n", + "* Our function will be called `isPalindrome()`.\n", + "* It will accept one **argument** called `txt`, which is a string.\n", + "* It will **return** either True (if `txt` is a palindrome) or `False` (if `txt`\n", + " is not a palindrome).\n", + " \n", + "
\n", + "\n", + "## How can we test along the way?\n", + "We will use the following test cases to check our function as we build it:\n", + "\n", + "The following should all return `True`:\n", + "```\n", + "isPalindrome('wow')\n", + "isPalindrome('12a3a21')\n", + "isPalindrome('Anna')\n", + "isPalindrome('race car')\n", + "isPalindrome('Was it a cat I saw?')\n", + "```\n", + "\n", + "The following should all return `False`:\n", + "```\n", + "isPalindrome('wowza')\n", + "isPalindrome('123a21')\n", + "isPalindrome('<3 mom <3')\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Class review\n", + "\n", + "## Recommended for evereyone:\n", + "\n", + "- Below is the code we wrote in class together, with a few tweaks.\n", + "- Read it, and try to explain it to another (real or imaginary) human, line by line.\n", + "- If you have any questions, write them down.\n", + " - Look your questions up online\n", + " - Investigate your questions by playing with the code\n", + " - Or bring your questions to a tutoring session to discuss together" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Define our function, called isPalindrome().\n", + "def isPalindrome(txt):\n", + " \"\"\"Check whether input text is a palindrome.\n", + " \n", + " Return True if input text is a palindrome, and\n", + " False if input text is not a palindrome.\n", + " \n", + " Arguments\n", + " txt (String): input text to check\n", + " Returns\n", + " answer (Boolean): whether or not text is a palindrome\n", + " \"\"\"\n", + " # Normalize the string\n", + " # Lowercase all of the text (e.g. Anna -> anna)\n", + " txt = txt.lower()\n", + " txt = txt.replace(' ', '')\n", + " txt = txt.replace('?', '')\n", + " \n", + " # Get the string spelled forward\n", + " forward = txt\n", + " \n", + " # Get the string spelled backward\n", + " backward = txt[::-1]\n", + " \n", + " # If the two strings are equal, then the answer is True\n", + " # Else, the answer is False\n", + " if forward == backward:\n", + " answer = True\n", + " else:\n", + " answer = False\n", + "\n", + " # Return the answer (either True/False)\n", + " return answer\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Going further\n", + "\n", + "## Recommended for people looking for a bit more challenge:\n", + "\n", + "- Read the following cell of code.\n", + "- Note that there are `TODO` comments throughout the code. `TODO` is a [conventional](https://stackoverflow.com/questions/9499039/where-does-the-todo-convention-come-from#:~:text=TODO%20means%20%22to%20do%22.,someone%20will%20need%20to%20do.)\n", + " placeholder a yet-to-be-completed task.\n", + "- Add comments to the code where the `TODOs` instruct.\n", + " - Some tactics for understanding what the code does:\n", + " - Comment out certain parts and re-run the code. See what happens differently.\n", + " - Add `print()` statements thoughout.\n", + "- Uncomment the last two lines where the final `TODO` instructs.\n", + " - What happens? Can you explain why?\n", + " - Edit the `isPalindrome()` function above so that the final two lines `Pass`.\n", + "- In a new cell at the bottom of the notebook, try running the following code:\n", + "\n", + "```\n", + "import re\n", + " \n", + "txt = 'Hello!?'\n", + "txt = re.sub('[^\\w\\d]', '', txt)\n", + "print(txt)\n", + "```\n", + "\n", + "- What is `re`? Why might we have shown you this?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n" + ] + } + ], + "source": [ + "def test(condition, result):\n", + " \"\"\"TODO: Add a short descirption of the function here.\n", + " \n", + " Arguments:\n", + " TODO: Add arguments description here, if applicable.\n", + " \"\"\"\n", + " # TODO: Add comment\n", + " if isPalindrome(condition) == result:\n", + " print('Pass')\n", + " # TODO: Add comment\n", + " else:\n", + " print ('Fail')\n", + "\n", + "# TODO: Add comment\n", + "test('wow', True)\n", + "test('12a3a21', True)\n", + "test('Anna', True)\n", + "test('race car', True)\n", + "test('Was it a cat I saw?', True)\n", + "test('wowza', False)\n", + "test('123a21', False)\n", + "test('<3 mom <3', False)\n", + "# TODO: Uncomment the following lines\n", + "# test('Was it a cat I saw?!', True)\n", + "# test('race-car', True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Example creative work\n", + "\n", + "## Recommended for anyone interested in *creative* coding\n", + "\n", + "Read [2002: A Palindrome Story by Nick Montfort & William Gillespie](http://spinelessbooks.com/2002/palindrome/index.html).
\n", + "\n", + "- How might this be made?\n", + "- What else could you imagine making with the code we've written here?" + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/exercises/Madlibs_exercise_answers.ipynb b/Week_03/exercises/Madlibs_exercise_answers.ipynb new file mode 100644 index 0000000..4b767e0 --- /dev/null +++ b/Week_03/exercises/Madlibs_exercise_answers.ipynb @@ -0,0 +1,157 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Encrypted Invitation woo!\n", + "\n", + "This exercise is built based on the madlibs invitation generator we made in class.\n", + "\n", + "We are going to create an encrypted event `invitation function`.\n", + "\n", + "The starter string:\n", + "```\n", + " Let's play games on Thursday\n", + " \n", + "```\n", + "\n", + "The ending outcomes:\n", + "1. a reversed message\n", + "\n", + "```\n", + "\n", + " \"yadsruhT no semag yalp s'teL\"\n", + "\n", + "\n", + "```\n", + "\n", + "2. a dashed message \n", + "\n", + "```\n", + "\n", + " \"L-e-t-'-s- -p-l-a-y- -g-a-m-e-s- -o-n- -T-h-u-r-s-d-a-y\"\n", + " \n", + "```\n", + "\n", + "3. numbered message\n", + "\n", + "```\n", + "\n", + " Let's play games on day 4 of the week\n", + " I want to see you on day 3 of the week\n", + " \n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "yadsruhT no semag yalp s'teL\n" + ] + } + ], + "source": [ + "# reversed message solution\n", + "string = \"Let's play games on Thursday\"\n", + "print(string[::-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "L-e-t-'-s- -p-l-a-y- -g-a-m-e-s- -o-n- -T-h-u-r-s-d-a-y\n" + ] + } + ], + "source": [ + "# dashed string solution\n", + "string = \"Let's play games on Thursday\"\n", + "newstring = '-'.join(string)\n", + "print(newstring)" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Let's play games on day 6 of the week.\n" + ] + } + ], + "source": [ + "# numbered message solution\n", + "def daytonum(str):\n", + " days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']\n", + " day_check = str.split(' ')[-1]\n", + " print(\"Let's play games on day %d of the week.\" % (days.index(day_check) + 1))\n", + "\n", + "daytonum(\"I want to see you on Saturday\")" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Let's play games on Thursday\n" + ] + } + ], + "source": [ + "string = \"Let's play games on Thursday\"\n", + "string.replace('play','AA')\n", + "print(string)" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/exercises/README.md b/Week_03/exercises/README.md new file mode 100644 index 0000000..4a7d50b --- /dev/null +++ b/Week_03/exercises/README.md @@ -0,0 +1 @@ +# Exercises for Week 3. diff --git a/Week_03/exercises/lexical_richness_scorer.ipynb b/Week_03/exercises/lexical_richness_scorer.ipynb new file mode 100644 index 0000000..e165632 --- /dev/null +++ b/Week_03/exercises/lexical_richness_scorer.ipynb @@ -0,0 +1,663 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Get the 'lexical richness' of a piece of text\n", + "\n", + "We're going to write a function that accepts any input text. It will return to us a \"lexical richness score\" for that text.\n", + "\n", + "In the process, we're going to see the following in use:\n", + "\n", + "- Strings\n", + "- String methods\n", + "- Lists\n", + "- List methods\n", + "- Mathematical operations\n", + "- Functions" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Store string data in a variable called 'text'.\n", + "# (This string is from 'Doorway to Distruction,'\n", + "# a randomly chosen book from the Gutenberg Library of ebooks).\n", + "\n", + "text = \"\"\"\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "Old Kelvin Martin strained futilely against the rope that held\n", + "immovable his thin wrists. A crimsoned bruise raced across his forehead\n", + "where Vance had slugged him with a heavy hand.\n", + "\n", + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "The scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Print the text.\n", + "\n", + "print(text)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists. a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand.\n", + "\n", + "\"don't be a complete fool, vance!\" he said harshly. \"that machine can't\n", + "bring you anything but trouble!\"\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room.\n", + "\n" + ] + } + ], + "source": [ + "# Lowercase all text.\n", + "\n", + "text_lower = text.lower()\n", + "print(text_lower)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "old kelvin martin strained futilely against the rope that held\n", + "immovable his thin wrists a crimsoned bruise raced across his forehead\n", + "where vance had slugged him with a heavy hand\n", + "\n", + "don't be a complete fool vance he said harshly that machine can't\n", + "bring you anything but trouble\n", + "\n", + "the scientist's burly assistant glanced wearily up from where he\n", + "coupled heavy batteries in series at the rear of the glittering machine\n", + "that entirely filled one corner of the windowless room\n", + "\n" + ] + } + ], + "source": [ + "# Remove all unnecessary punctuation.\n", + "# Note that there are better ways to do this that we haven't yet learned.\n", + "\n", + "text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + "print(text_clean)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['old', 'kelvin', 'martin', 'strained', 'futilely', 'against', 'the', 'rope', 'that', 'held', 'immovable', 'his', 'thin', 'wrists', 'a', 'crimsoned', 'bruise', 'raced', 'across', 'his', 'forehead', 'where', 'vance', 'had', 'slugged', 'him', 'with', 'a', 'heavy', 'hand', \"don't\", 'be', 'a', 'complete', 'fool', 'vance', 'he', 'said', 'harshly', 'that', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble', 'the', \"scientist's\", 'burly', 'assistant', 'glanced', 'wearily', 'up', 'from', 'where', 'he', 'coupled', 'heavy', 'batteries', 'in', 'series', 'at', 'the', 'rear', 'of', 'the', 'glittering', 'machine', 'that', 'entirely', 'filled', 'one', 'corner', 'of', 'the', 'windowless', 'room']\n" + ] + } + ], + "source": [ + "# Split the text into a list of words separated by whitespace.\n", + "\n", + "text_data = text_clean.split()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'a', 'a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'he', 'heavy', 'heavy', 'held', 'him', 'his', 'his', 'immovable', 'in', 'kelvin', 'machine', 'machine', 'martin', 'of', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'that', 'that', 'the', 'the', 'the', 'the', 'the', 'thin', 'trouble', 'up', 'vance', 'vance', 'wearily', 'where', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Sort the list alphabetically.\n", + "\n", + "text_data.sort()\n", + "print(text_data)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "78\n" + ] + } + ], + "source": [ + "# Count the total number of words.\n", + "\n", + "num_words = len(text_data)\n", + "print(num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['a', 'across', 'against', 'anything', 'assistant', 'at', 'batteries', 'be', 'bring', 'bruise', 'burly', 'but', \"can't\", 'complete', 'corner', 'coupled', 'crimsoned', \"don't\", 'entirely', 'filled', 'fool', 'forehead', 'from', 'futilely', 'glanced', 'glittering', 'had', 'hand', 'harshly', 'he', 'heavy', 'held', 'him', 'his', 'immovable', 'in', 'kelvin', 'machine', 'martin', 'of', 'old', 'one', 'raced', 'rear', 'room', 'rope', 'said', \"scientist's\", 'series', 'slugged', 'strained', 'that', 'the', 'thin', 'trouble', 'up', 'vance', 'wearily', 'where', 'windowless', 'with', 'wrists', 'you']\n" + ] + } + ], + "source": [ + "# Let's make a unique list of words.\n", + "# I.e. every word in the text is including in this list\n", + "# exactly once.\n", + "\n", + "unique_words = []\n", + "\n", + "for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + "\n", + "print(unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "63\n" + ] + } + ], + "source": [ + "# Let's count the number of unique words.\n", + "\n", + "num_unique_words = len(unique_words)\n", + "print(num_unique_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.8076923076923077" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This is enough information for a decent\n", + "# measure of lexical \"richness\".\n", + "\n", + "num_unique_words / num_words" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Let's make all of this into a function.\n", + "\n", + "def printLexicalRichness(text):\n", + " # Lowercase the text\n", + " text_lower = text.lower()\n", + " # Clean unnecessary punctuation\n", + " text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + " # Split text into list\n", + " text_data = text_clean.split()\n", + " # Get the total words in the list\n", + " num_words = len(text_data)\n", + " # Make a separate unique list\n", + " unique_words = []\n", + " for word in text_data:\n", + " if word not in unique_words:\n", + " unique_words.append(word)\n", + " # Get the number of unique words\n", + " num_unique_words = len(unique_words)\n", + " \n", + " # Print the stat.\n", + " print(num_unique_words / num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.3717331499312242\n" + ] + } + ], + "source": [ + "# Rather than get the richness of just a couple lines,\n", + "# let's get the richness of a huge chunk of text.\n", + "\n", + "book = \"\"\"\n", + "Special Investigator Billy Neville was annoyed, and for more reasons\n", + "than one. He had just done a tedious year in the jungles of Venus\n", + "stamping out the gooroo racket and then, on his way home to a\n", + "well-deserved leave and rest, had been diverted to Mars for a swift\n", + "clean-up of the diamond-mine robbery ring. And now, when he again\n", + "thought he would be free for a while, he found himself shunted to\n", + "little Pallas, capital of the Asteroid Confederation. But clever,\n", + "patient Colonel Frawley, commandant of all the Interplanetary Police in\n", + "the belt, merely smiled indulgently while Neville blew off his steam.\n", + "\n", + "\"You say,\" said Neville, still ruffled, \"that there has been a growing\n", + "wave of blackmail and extortion all over the System, coupled with a\n", + "dozen or so instances of well-to-do, respectable persons disappearing\n", + "without a trace. And you say that that has been going on for a couple\n", + "of years and several hundred of our crack operatives have been working\n", + "on it, directed by the best brains of the force, and yet haven't got\n", + "anywhere. And that up to now there have been no such cases develop in\n", + "the asteroids. Well, what do you want _me_ for? What's the emergency?\"\n", + "\n", + "The colonel laughed and dropped the ash from his cigar, preparatory to\n", + "lying back in his chair and taking another long, soothing drag. The\n", + "office of the Chief Inspector of the A.C. division of the I.P. was not\n", + "only well equipped for the work it had to do, but for comfort.\n", + "\n", + "\"I am astonished,\" he remarked, \"to hear an experienced policeman\n", + "indulge in such loose talk. Who said anything about having had the\n", + "_best_ brains on the job? Or that no progress had been made? Or that\n", + "there was no emergency? Any bad crime situation is always an emergency,\n", + "no matter how long it lasts. Which is all the more reason why we have\n", + "to break it up, and quickly. I tell you, things are becoming very\n", + "serious. Lifelong partners in business are becoming suspicious and\n", + "secretive toward each other; husbands and wives are getting jittery and\n", + "jealous. Nobody knows whom to trust. The most sacred confidences have a\n", + "way of leaking out. Then they are in the market for the highest bidder.\n", + "No boy, this thing is a headache. I never had a worse.\"\n", + "\n", + "\"All right, all right,\" growled Neville, resignedly. \"I'm stuck. Shoot!\n", + "How did it begin, and what do you know?\"\n", + "\n", + " * * * * *\n", + "\n", + "The colonel reached into a drawer and pulled out a fat jacket bulging\n", + "with papers, photostats, and interdepartmental reports.\n", + "\n", + "\"It began,\" he said, \"about two years ago, on Io and Callisto. It\n", + "spread all over the Jovian System and soured Ganymede and Europa.\n", + "The symptoms were first the disappearances of several prominent\n", + "citizens, followed by a wave of bankruptcies and suicides on both\n", + "planetoids. Nobody complained to the police. Then a squad of our\n", + "New York men picked up a petty chiseler who was trying to gouge the\n", + "Jovian Corporation's Tellurian office out of a large sum of money on\n", + "the strength of some damaging documents he possessed relating to a\n", + "hidden scandal in the life of the New York manager. From that lead,\n", + "they picked up a half-dozen other small fry extortionists and even\n", + "managed to grab their higher-up--a sort of middleman who specialized\n", + "in exploiting secret commercial information and scandalous material\n", + "about individuals. There the trail stopped. They put him through the\n", + "mill, but all he would say is that a man approached him with the\n", + "portfolio, sold him on its value for extortion purposes, and collected\n", + "in advance. There could be no follow up for the reason that after the\n", + "first transaction what profits the local gang could make out of the\n", + "dirty work would be their own.\"\n", + "\n", + "\"Yes,\" said Neville, \"I know the racket. When they handle it that way\n", + "it's hard to beat. You get any amount of minnows, but the whales get\n", + "away.\"\n", + "\n", + "\"Right. The disturbing thing about the contents of the portfolio was\n", + "the immense variety of secrets it contained and that it was evidently\n", + "prepared by one man. There were, for example, secret industrial\n", + "formulas evidently stolen for sale to a competitor. The bulk of it was\n", + "other commercial items, such as secret credit reports, business volume,\n", + "and the like. But there was a good deal of rather nasty personal stuff,\n", + "too. It was a gold mine of information for an unscrupulous blackmailer,\n", + "and every bit of it originated on Callisto. Now, whom do you think,\n", + "could have been in a position to compile it?\"\n", + "\n", + "\"The biggest corporation lawyer there, I should guess,\" said Neville.\n", + "\"Priests and doctors know a lot of personal secrets, but a good lawyer\n", + "manages to learn most everything.\"\n", + "\n", + "\"Right. Very right. We sent men to Callisto and learned that some\n", + "months earlier the most prominent lawyer of the place had announced one\n", + "day he must go over to Io to arrange some contracts. He went to Io,\n", + "all right, but was never seen again after he stepped out of the ship.\n", + "It was shortly after, that the wave of Callistan suicides and business\n", + "failures took place.\"\n", + "\n", + "\"All right,\" agreed Neville, \"so what? It has happened before. Even the\n", + "big ones go wrong now and then.\"\n", + "\n", + "\"Yes, but wait. That fellow had nothing to go wrong about. He was\n", + "tremendously successful, rich, happily married, and highly respected\n", + "for his outstanding integrity. Yet he could hardly have been kidnaped,\n", + "as there has never been a ransom demand. Nor has there ever been such a\n", + "demand in any of the other cases similar to it.\n", + "\n", + "\"The next case to be partially explained was that of the disappearance\n", + "of the president of the Jupiter Trust Company at Ionopolis. All the\n", + "most vital secrets of that bank turned up later in all parts of the\n", + "civilized system. We nabbed some peddlers, but it was the same story\n", + "as with the first gang. The facts are all here in this jacket. After a\n", + "little you can read the whole thing in detail.\"\n", + "\n", + "\"Uh, huh,\" grunted Neville, \"I'm beginning to see. But why _me_, and\n", + "why at Pallas?\"\n", + "\n", + "\"Because you've never worked in the asteroids and are not known here\n", + "to any but the higher officers. Among other secrets this ring has, are\n", + "a number of police secrets. That is why setting traps for them is so\n", + "difficult. I haven't told you that one of their victims seems to have\n", + "been one of us. That was Jack Sarkins, who was district commander at\n", + "Patroclus. He received an apparently genuine ethergram one day--and it\n", + "was in our most secret code--telling him to report to Mars at once.\n", + "He went off, alone, in his police rocket. He never got there. As to\n", + "Pallas, the reason you are here is because the place so far is clean.\n", + "Their system is to work a place just once and never come back. They\n", + "milk it dry the first time and there is no need to. Since we have no\n", + "luck tracing them after the crime, we are going to try a plant and wait\n", + "for the crime to come to it. You are the plant.\"\n", + "\n", + "\"I see,\" said Neville slowly. He was interested, but not enthusiastic.\n", + "\"Some day, somehow, someone is coming here and in some manner\n", + "force someone to yield up all the local dirt and then arrange his\n", + "disappearance. My role is to break it up before it happens. Sweet!\"\n", + "\n", + "\"You have such a way of putting things, Neville,\" chuckled the colonel,\n", + "\"but you do get the point.\"\n", + "\n", + "He rose and pushed the heavy folder toward his new aide.\n", + "\n", + "\"Bone this the rest of the afternoon. I'll be back.\"\n", + "\n", + " * * * * *\n", + "\n", + "It was quite late when Colonel Frawley returned and asked Neville\n", + "cheerily how he was getting on.\n", + "\n", + "\"I have the history,\" Neville answered, slamming the folder shut, \"and\n", + "a glimmering of what you are shooting at. This guy Simeon Carstairs, I\n", + "take it, is the local man you have picked as the most likely prospect\n", + "for your Master Mind crook to work on?\"\n", + "\n", + "\"He is. He is perfect bait. He is the sole owner of the Radiation\n", + "Extraction Company which has a secret process that Tellurian Radiant\n", + "Corporation has made a standing offer of five millions for. He controls\n", + "the local bank and often sits as magistrate. In addition, he has\n", + "substantial interests in Vesta and Juno industries. He probably knows\n", + "more about the asteroids and the people on them than any other living\n", + "man. Moreover, his present wife is a woman with an unhappy past and who\n", + "happens also to be related to an extremely wealthy Argentine family.\n", + "Any ring of extortionists who could worm old Simeon's secrets out of\n", + "him could write their own ticket.\"\n", + "\n", + "\"So I am to be a sort of private shadow.\"\n", + "\n", + "\"Not a bit of it. _I_ am his bodyguard. We are close friends and lately\n", + "I have made it a rule to be with him part of the time every day. No,\n", + "your role is that of observer from the sidelines. I shall introduce\n", + "you as the traveling representative of the London uniform house that\n", + "has the police contract. That will explain your presence here and your\n", + "occasional calls at headquarters. You might sell a few suits of clothes\n", + "on the side, or at least solicit them. Work that out for yourself.\"\n", + "\n", + "Neville grimaced. He was not fond of plainclothes work.\n", + "\n", + "\"But come, fellow. You've worked hard enough for one day. Go up to\n", + "my room and get into cits. Then I'll take you over to the town and\n", + "introduce you around. After that we'll go to a show. The showboat\n", + "landed about an hour ago.\"\n", + "\n", + "\"Showboat? What the hell is a showboat?\"\n", + "\n", + "\"I forget,\" said the colonel, \"that your work has been mostly on the\n", + "heavy planets where they have plenty of good playhouses in the cities.\n", + "Out here among these little rocks the diversions are brought around\n", + "periodically and peddled for the night. The showboat, my boy, is a\n", + "floating theater--a space ship with a stage and an auditorium in it, a\n", + "troupe of good actors and a cracking fine chorus. This one has been\n", + "making the rounds quite a while, though it never stopped here before\n", + "until last year. They say the show this year is even better. It is the\n", + "\"Lunar Follies of 2326,\" featuring a chorus of two hundred androids\n", + "and with Lilly Fitzpatrick and Lionel Dustan in the lead. Tonight, for\n", + "a change, you can relax and enjoy yourself. We can get down to brass\n", + "tacks tomorrow.\"\n", + "\n", + "\"Thanks, chief,\" said Neville, grinning from ear to ear. The\n", + "description of the showboat was music to his ears, for it had been\n", + "a long time since he had seen a good comedy and he felt the need of\n", + "relief from his sordid workaday life.\n", + "\n", + "\"When you're in your makeup,\" the colonel added, \"come on down and I'll\n", + "take you over in my copter.\"\n", + "\n", + " * * * * *\n", + "\n", + "It did not take Billy Neville long to make his transformation to the\n", + "personality of a clothing drummer. Every special cop had to be an\n", + "expert at the art of quick shifts of disguise and Neville was rather\n", + "better than most. Nor did it take long for the little blue copter to\n", + "whisk them halfway around the knobby little planetoid of Pallas. It\n", + "eased itself through an airlock into a doomed town, and there the\n", + "colonel left it with his orderly.\n", + "\n", + "The town itself possessed little interest for Neville though his\n", + "trained photographic eye missed few of its details. It was much like\n", + "the smaller doomed settlements on the Moon. He was more interested\n", + "in meeting the local magnate, whom they found in his office in the\n", + "Carstairs Building. The colonel made the introductions, during which\n", + "Neville sized up the man. He was of fair height, stockily built, and\n", + "had remarkably frank and friendly eyes for a self-made man of the\n", + "asteroids. Not that there was not a certain hardness about him and a\n", + "considerable degree of shrewdness, but he lacked the cynical cunning\n", + "so often displayed by the pioneers of the outer system. Neville noted\n", + "other details as well--the beginning of a set of triple chins, a little\n", + "brown mole with three hairs on it alongside his nose, and the way a\n", + "stray lock of hair kept falling over his left eye.\n", + "\n", + "\"Let's go,\" said the colonel, as soon as the formalities were over.\n", + "\n", + "Neville had to borrow a breathing helmet from Mr. Carstairs, for he had\n", + "not one of his own and they had to walk from the far portal of the dome\n", + "across the field to where the showboat lay parked. He thought wryly,\n", + "as he put it on, that he went from one extreme to another--from Venus,\n", + "where the air was over-moist, heavy and oppressive from its stagnation,\n", + "to windy, blustery Mars, and then here, where there was no air at all.\n", + "\n", + "As they approached the grounded ship they saw it was all lit up and\n", + "throngs of people were approaching from all sides. Flood lamps threw\n", + "great letters on the side of the silvery hull reading, \"Greatest Show\n", + "of the Void--Come One, Come All--Your Money Back if Not Absolutely\n", + "Satisfied.\" They went ahead of the queue, thanks to the prestige of\n", + "the colonel and the local tycoon, and were instantly admitted. It took\n", + "but a moment to check their breathers at the helmet room and then the\n", + "ushers had them in tow.\n", + "\n", + "\"See you after the show, Mr. Allington,\" said the colonel to Neville,\n", + "\"I will be in Mr. Carstairs box.\"\n", + "\n", + " * * * * *\n", + "\n", + "Neville sank into a seat and watched them go. Then he began to take\n", + "stock of the playhouse. The seats were comfortable and commodious,\n", + "evidently having been designed to hold patrons clad in heavy-dust\n", + "space-suits. The auditorium was almost circular, one semi-circle being\n", + "taken up by the stage, the other by the tiers of seats. Overhead ranged\n", + "a row of boxes jutting out above the spectators below. Neville puzzled\n", + "for a long time over the curtain that shut off the stage. It seemed\n", + "very unreal, like the shimmer of the aurora, but it affected vision to\n", + "the extent that the beholder could not say with any certainty _what_\n", + "was behind it. It was like looking through a waterfall. Then there was\n", + "eerie music, too, from an unseen source, flooding the air with queer\n", + "melodies. People continued to pour in. The house gradually darkened and\n", + "as it did the volume and wildness of the music rose. Then there was a\n", + "deep bong, and lights went completely out for a full second. The show\n", + "was on.\n", + "\n", + "Neville sat back and enjoyed it. He could not have done otherwise,\n", + "for the sign on the hull had not been an empty plug. It was the best\n", + "show in the void--or anywhere else, for that matter. A spectral voice\n", + "that seemed to come from everywhere in the house announced the first\n", + "number--The Dance of the Wood-sprites of Venus. Instantly little\n", + "flickers of light appeared throughout the house--a mass of vari-colored\n", + "fireflies blinking off and on and swirling in dizzy spirals. They\n", + "steadied and grew, coalesced into blobs of living fire--ruby, dazzling\n", + "green, ethereal blue and yellow. They swelled and shrank, took on\n", + "human forms only to abandon them; purple serpentine figures writhed\n", + "among them, paling to silvery smoke and then expiring as a shower of\n", + "violet sparks. And throughout was the steady, maddening rhythm of the\n", + "dance tune, unutterably savage and haunting--a folk dance of the hill\n", + "tribes of Venus. At last, when the sheer beauty of it began to lull\n", + "the viewers into a hypnotic trance, there came the shrill blare of\n", + "massed trumpets and the throb of mighty tom-toms culminating in an\n", + "ear-shattering discord that broke the spell.\n", + "\n", + "The lights were on. The stage was bare. Neville sat up straighter and\n", + "looked, blinking. It was as if he were in an abandoned warehouse. And\n", + "then the scenery began to grow. Yes, grow. Almost imperceptible it was,\n", + "at first, then more distinct. Nebulous bodies appeared, wisps of smoke.\n", + "They wavered, took on shape, took on color, took on the appearance of\n", + "solidity. The scent began to have meaning. Part of the background was a\n", + "gray cliff undercut with a yawning cave. It was a scene from the Moon,\n", + "a hangout of the cliffdwellers, those refugees from civilization who\n", + "chose to live the wild life of the undomed Moon rather than submit to\n", + "the demands of a more ordered life.\n", + "\n", + "Characters came on. There was a little drama, well conceived and well\n", + "acted. When it was over, the scene vanished as it had come. A comedy\n", + "team came out next and this time the appropriate scenery materialized\n", + "at once as one of them stumbled over an imaginary log and fell on his\n", + "face. The log was not there when he tripped, but it was there by the\n", + "time his nose hit the stage, neatly turning the joke on his companion\n", + "who had started to laugh at his unreasonable fall.\n", + "\n", + "On the show went, one scene swiftly succeeding the next. A song that\n", + "took the fancy of the crowd was a plaintive ballad. It ran:\n", + "\n", + " _They tell me you did not treat me right,_\n", + " _Nor are grateful for all I've done._\n", + " _I fear you're fickle as a meteorite_\n", + " _Though my love's constant as the Sun._\"\"\"\n", + "\n", + "printLexicalRichness(book)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Going further\n", + "\n", + "- What other stats can you get?\n", + " - longest word?\n", + " - shortest word?\n", + " - most frequent word?\n", + "- For the super adventurers\n", + " - check out the `nltk` library, read it's documentation. Think about what it allows us to do better or differently. We'll cover this more later, but you can get a head start" + ] + }, + { + "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.4" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb b/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb new file mode 100644 index 0000000..f3fbcdd --- /dev/null +++ b/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb @@ -0,0 +1,222 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Palindrome - completed code & going further\n", + "\n", + "## What is a palindrome?\n", + "A palindrome is a word or phrase that is spelled the same forwards as backwards, like `wow`. Capitalization, whitespace, and punctuation are often ignored, so examples like `Anna`, `race car`, and `Was it a cat I saw?` are also palindromes.\n", + "\n", + "
\n", + "\n", + "## What are we going to make?\n", + "We are going to create a function that checks whether or not a given phrase is a palindrome. Here are our guidelines:\n", + "* Our function will be called `isPalindrome()`.\n", + "* It will accept one **argument** called `txt`, which is a string.\n", + "* It will **return** either True (if `txt` is a palindrome) or `False` (if `txt`\n", + " is not a palindrome).\n", + " \n", + "
\n", + "\n", + "## How can we test along the way?\n", + "We will use the following test cases to check our function as we build it:\n", + "\n", + "The following should all return `True`:\n", + "```\n", + "isPalindrome('wow')\n", + "isPalindrome('12a3a21')\n", + "isPalindrome('Anna')\n", + "isPalindrome('race car')\n", + "isPalindrome('Was it a cat I saw?')\n", + "```\n", + "\n", + "The following should all return `False`:\n", + "```\n", + "isPalindrome('wowza')\n", + "isPalindrome('123a21')\n", + "isPalindrome('<3 mom <3')\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Class review\n", + "\n", + "## Recommended for evereyone:\n", + "\n", + "- Below is the code we wrote in class together, with a few tweaks.\n", + "- Read it, and try to explain it to another (real or imaginary) human, line by line.\n", + "- If you have any questions, write them down.\n", + " - Look your questions up online\n", + " - Investigate your questions by playing with the code\n", + " - Or bring your questions to a tutoring session to discuss together" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Define our function, called isPalindrome().\n", + "def isPalindrome(txt):\n", + " \"\"\"Check whether input text is a palindrome.\n", + " \n", + " Return True if input text is a palindrome, and\n", + " False if input text is not a palindrome.\n", + " \n", + " Arguments\n", + " txt (String): input text to check\n", + " Returns\n", + " answer (Boolean): whether or not text is a palindrome\n", + " \"\"\"\n", + " # Normalize the string\n", + " # Lowercase all of the text (e.g. Anna -> anna)\n", + " txt = txt.lower()\n", + " txt = txt.replace(' ', '')\n", + " txt = txt.replace('?', '')\n", + " \n", + " # Get the string spelled forward\n", + " forward = txt\n", + " \n", + " # Get the string spelled backward\n", + " backward = txt[::-1]\n", + " \n", + " # If the two strings are equal, then the answer is True\n", + " # Else, the answer is False\n", + " if forward == backward:\n", + " answer = True\n", + " else:\n", + " answer = False\n", + "\n", + " # Return the answer (either True/False)\n", + " return answer\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Going further\n", + "\n", + "## Recommended for people looking for a bit more challenge:\n", + "\n", + "- Read the following cell of code.\n", + "- Note that there are `TODO` comments throughout the code. `TODO` is a [conventional](https://stackoverflow.com/questions/9499039/where-does-the-todo-convention-come-from#:~:text=TODO%20means%20%22to%20do%22.,someone%20will%20need%20to%20do.)\n", + " placeholder a yet-to-be-completed task.\n", + "- Add comments to the code where the `TODOs` instruct.\n", + " - Some tactics for understanding what the code does:\n", + " - Comment out certain parts and re-run the code. See what happens differently.\n", + " - Add `print()` statements thoughout.\n", + "- Uncomment the last two lines where the final `TODO` instructs.\n", + " - What happens? Can you explain why?\n", + " - Edit the `isPalindrome()` function above so that the final two lines `Pass`.\n", + "- In a new cell at the bottom of the notebook, try running the following code:\n", + "\n", + "```\n", + "import re\n", + " \n", + "txt = 'Hello!?'\n", + "txt = re.sub('[^\\w\\d]', '', txt)\n", + "print(txt)\n", + "```\n", + "\n", + "- What is `re`? Why might we have shown you this?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n", + "Pass\n" + ] + } + ], + "source": [ + "def test(condition, result):\n", + " \"\"\"TODO: Add a short descirption of the function here.\n", + " \n", + " Arguments:\n", + " TODO: Add arguments description here, if applicable.\n", + " \"\"\"\n", + " # TODO: Add comment\n", + " if isPalindrome(condition) == result:\n", + " print('Pass')\n", + " # TODO: Add comment\n", + " else:\n", + " print ('Fail')\n", + "\n", + "# TODO: Add comment\n", + "test('wow', True)\n", + "test('12a3a21', True)\n", + "test('Anna', True)\n", + "test('race car', True)\n", + "test('Was it a cat I saw?', True)\n", + "test('wowza', False)\n", + "test('123a21', False)\n", + "test('<3 mom <3', False)\n", + "# TODO: Uncomment the following lines\n", + "# test('Was it a cat I saw?!', True)\n", + "# test('race-car', True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Example creative work\n", + "\n", + "## Recommended for anyone interested in *creative* coding\n", + "\n", + "Read [2002: A Palindrome Story by Nick Montfort & William Gillespie](http://spinelessbooks.com/2002/palindrome/index.html).
\n", + "\n", + "- How might this be made?\n", + "- What else could you imagine making with the code we've written here?" + ] + }, + { + "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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}