From d9eb427d29bd676d414b63198d2e39daf784bd19 Mon Sep 17 00:00:00 2001 From: FifiXie <41806279+FifiXie@users.noreply.github.com> Date: Mon, 1 Jun 2020 16:28:43 -0400 Subject: [PATCH 01/24] changed title --- ...Week 2 Math, Logic, Loops-checkpoint.ipynb | 1204 +++++++++++++++++ Week_02/Week 2 Math, Logic, Loops.ipynb | 4 +- 2 files changed, 1206 insertions(+), 2 deletions(-) create mode 100644 Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb 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..1709663 --- /dev/null +++ b/Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb @@ -0,0 +1,1204 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Types" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### (Numbers)" + ] + }, + { + "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", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, + "execution_count": 1, + "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", + "execution_count": 2, + "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", + "execution_count": 3, + "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", + "execution_count": 4, + "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", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "list_with_words= [\"this\", \"is\", \"a\", \"list\", \"we\", \"created\"]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "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", + "execution_count": 7, + "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", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "created\n" + ] + } + ], + "source": [ + "#print the last item\n", + "print(list_with_words[-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "we\n" + ] + } + ], + "source": [ + "#print second last item,\n", + "print(list_with_words[-2])" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "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", + "execution_count": 11, + "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", + "execution_count": 12, + "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": [ + "## Basic Operator with Numbers" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "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": 14, + "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": 15, + "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": 16, + "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": [ + "### Short Hand" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "8\n" + ] + } + ], + "source": [ + "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)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "6\n" + ] + } + ], + "source": [ + "x=2\n", + "x*=3 # x=2*3 \n", + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "9.0\n" + ] + } + ], + "source": [ + "y = 18\n", + "y/=2 # y=18/2 \n", + "print(y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Type Convertion / Cast" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "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", + "execution_count": 22, + "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", + "execution_count": 23, + "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", + "execution_count": 24, + "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", + "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'" + ] + } + ], + "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", + "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" + ] + } + ], + "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": [ + "## 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, + "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", + "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 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Identity operators: \"is not\" and \"is\" " + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "True\n" + ] + } + ], + "source": [ + "x1 = 5\n", + "y1 = 5\n", + "x2 = 'Hello'\n", + "y2 = 'Hello'\n", + "\n", + "# Output: False\n", + "print(x1 is not y1)\n", + "\n", + "# Output: True\n", + "print(x2 is y2)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### membership operators: \"not in\" and \"in\" " + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "False\n", + "False\n" + ] + } + ], + "source": [ + "x = 'Hello world'\n", + "\n", + "# Output: True\n", + "print('H' in x)\n", + "\n", + "# 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### If Statements" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition not met\n" + ] + } + ], + "source": [ + "x = False\n", + "if x: # this means if x is true \n", + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition met\n" + ] + } + ], + "source": [ + "x = False\n", + "if not x: # this means condition is true because 'not false' is true \n", + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { + "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 \")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "### Two easy to understand operators are and and or. They do exactly what they sound like:" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition met\n", + "condition met\n" + ] + } + ], + "source": [ + "if 1 < 2 and 4 > 2:\n", + " print(\"condition met\")\n", + "\n", + "if 4 < 10 or 1 > 2:\n", + " print(\"condition met\")" + ] + }, + { + "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 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### nested IF statements" + ] + }, + { + "cell_type": "code", + "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.\")" + ] + }, + { + "cell_type": "code", + "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\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### For Loops " + ] + }, + { + "cell_type": "code", + "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)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Avoid infinte loops " + ] + }, + { + "cell_type": "code", + "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)" + ] + }, + { + "cell_type": "code", + "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", + " " + ] + }, + { + "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_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, From e01e8ceb8e0818ea50d483f3378807ffca78c093 Mon Sep 17 00:00:00 2001 From: Lan Zhang Date: Wed, 3 Jun 2020 13:07:15 -0400 Subject: [PATCH 02/24] k --- .../FlippingCoinExample-checkpoint.ipynb | 101 ++ ...Week 2 Math, Logic, Loops-checkpoint.ipynb | 1074 +++++++++++++++++ 2 files changed, 1175 insertions(+) create mode 100644 Week_02/.ipynb_checkpoints/FlippingCoinExample-checkpoint.ipynb create mode 100644 Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb 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..158044e --- /dev/null +++ b/Week_02/.ipynb_checkpoints/Week 2 Math, Logic, Loops-checkpoint.ipynb @@ -0,0 +1,1074 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 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": [ + "## Types" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Numbers" + ] + }, + { + "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", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, + "execution_count": 5, + "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", + "execution_count": 8, + "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", + "execution_count": 9, + "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", + "execution_count": 5, + "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", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "list_with_words= [\"this\", \"is\", \"a\", \"list\", \"we\", \"created\"]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "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", + "execution_count": 15, + "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", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "created\n" + ] + } + ], + "source": [ + "#print the last item\n", + "print(list_with_words[-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "we\n" + ] + } + ], + "source": [ + "#print second last item,\n", + "print(list_with_words[-2])" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "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", + "execution_count": 6, + "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", + "execution_count": 7, + "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": [ + "## Comparison & Boolean" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "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": 6, + "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": 8, + "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": 9, + "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": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n" + ] + } + ], + "source": [ + "x = 5\n", + "\n", + "print(not(x > 3 and x < 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Identity Operators" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "True\n", + "False\n" + ] + } + ], + "source": [ + "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)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "x = [\"apple\", \"banana\"]\n", + "\n", + "print(\"banana\" in x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Type Convertion / Cast" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "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", + "execution_count": 15, + "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", + "execution_count": 16, + "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", + "execution_count": 13, + "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", + "execution_count": null, + "metadata": {}, + "outputs": [], + "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", + "execution_count": null, + "metadata": {}, + "outputs": [], + "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": [ + "## Logical Operations " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Logical operators are the and, or, not operators." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "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", + "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)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Identity operators: \"is not\" and \"is\" " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "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)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### membership operators: \"not in\" and \"in\" " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "x = 'Hello world'\n", + "y = {1:'a',2:'b'}\n", + "\n", + "# Output: True\n", + "print('H' in x)\n", + "\n", + "# 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)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### If Statements" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition not met\n" + ] + } + ], + "source": [ + "x = False\n", + "if x : # this if x is true \n", + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "condition met\n" + ] + } + ], + "source": [ + "x = False\n", + "if not x : # this means condition is true because not false is true \n", + " print(\"condition met\")\n", + "else:\n", + " print(\"condition not met\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## This and that or something else\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "Two easy to understand operators are and and or. They do exactly what they sound like:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "if 1 < 2 and 4 > 2:\n", + " print(\"condition met\")\n", + "\n", + "if 1 > 2 and 4 < 10:x\n", + " print(\"condition not met\")\n", + "\n", + "if 4 < 10 or 1 < 2:\n", + " print(\"condition met\")" + ] + }, + { + "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": "markdown", + "metadata": {}, + "source": [ + "### using breaks" + ] + }, + { + "cell_type": "code", + "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 " + ] + }, + { + "cell_type": "code", + "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\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nested if statements " + ] + }, + { + "cell_type": "code", + "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.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## elif" + ] + }, + { + "cell_type": "code", + "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\")" + ] + }, + { + "cell_type": "code", + "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 " + ] + }, + { + "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 +} From 3c02b31917996eab0d235a050db0be0cdec6b57e Mon Sep 17 00:00:00 2001 From: Lan Zhang Date: Wed, 3 Jun 2020 14:46:47 -0400 Subject: [PATCH 03/24] typo --- Week_03/{tuples_lists.ipynb => cheatsheet_tuples_lists.ipynb} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Week_03/{tuples_lists.ipynb => cheatsheet_tuples_lists.ipynb} (100%) diff --git a/Week_03/tuples_lists.ipynb b/Week_03/cheatsheet_tuples_lists.ipynb similarity index 100% rename from Week_03/tuples_lists.ipynb rename to Week_03/cheatsheet_tuples_lists.ipynb From 1234c8c53748d249428e2ec5ff44be429585538b Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 16:44:08 -0400 Subject: [PATCH 04/24] reorg the dir --- Week_03/.DS_Store | Bin 0 -> 6148 bytes .../cheatsheet_tuples_lists.ipynb | 0 .../madlibs_event_invitation.ipynb | 0 .../madlibs_event_invitation_empty.ipynb | 0 4 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 Week_03/.DS_Store rename Week_03/{ => cheatsheets}/cheatsheet_tuples_lists.ipynb (100%) rename Week_03/{ => class_code}/madlibs_event_invitation.ipynb (100%) rename Week_03/{ => class_code}/madlibs_event_invitation_empty.ipynb (100%) diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..ff3852cef46f6cd5f87637ee37d74c298d989776 GIT binary patch literal 6148 zcmeHK%TB{U3>-rbrM>jXaesk7SXJc<_y8zPB#j6DXtpyjonR9{XgcZr>`wq$+thi2Gy z&wbx1alw)fTW$|{8&AQkvhK)(-#u2=&{NBeXz*a$$JF>S`R%@V|-31ST#9hsqtQ;ANM7%{}@%$KOE zfup0-Au)VNoGdY+h@H;o7b}NU$Bd~!DsZlV&fc_@_WyhO5A(m)q@@C>z#mmWW}Ao2 znlBf Date: Wed, 3 Jun 2020 16:47:18 -0400 Subject: [PATCH 05/24] Delete .DS_Store --- Week_03/.DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Week_03/.DS_Store diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store deleted file mode 100644 index ff3852cef46f6cd5f87637ee37d74c298d989776..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%TB{U3>-rbrM>jXaesk7SXJc<_y8zPB#j6DXtpyjonR9{XgcZr>`wq$+thi2Gy z&wbx1alw)fTW$|{8&AQkvhK)(-#u2=&{NBeXz*a$$JF>S`R%@V|-31ST#9hsqtQ;ANM7%{}@%$KOE zfup0-Au)VNoGdY+h@H;o7b}NU$Bd~!DsZlV&fc_@_WyhO5A(m)q@@C>z#mmWW}Ao2 znlBf Date: Wed, 3 Jun 2020 16:49:32 -0400 Subject: [PATCH 06/24] dir organization --- Week_03/.gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 Week_03/.gitignore 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 From 2c1d2b0e607a4a9a5324f9bfb3f8a533e8ae0ac7 Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 16:56:16 -0400 Subject: [PATCH 07/24] add cheatsheet readme --- Week_03/cheatsheets/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 Week_03/cheatsheets/README.md diff --git a/Week_03/cheatsheets/README.md b/Week_03/cheatsheets/README.md new file mode 100644 index 0000000..ac5adb0 --- /dev/null +++ b/Week_03/cheatsheets/README.md @@ -0,0 +1 @@ +Commented notebooks with basic information, listed textbook-style. From 69489e491f82a33076fb5910aa0d3cf673d1947a Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 16:58:15 -0400 Subject: [PATCH 08/24] add class_code readme --- Week_03/class_code/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 Week_03/class_code/README.md 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. From 53007d33ee859efa0f3b45dcb4309635eb54a892 Mon Sep 17 00:00:00 2001 From: annagarbier Date: Wed, 3 Jun 2020 16:58:41 -0400 Subject: [PATCH 09/24] Update README.md --- Week_03/cheatsheets/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week_03/cheatsheets/README.md b/Week_03/cheatsheets/README.md index ac5adb0..baea5f7 100644 --- a/Week_03/cheatsheets/README.md +++ b/Week_03/cheatsheets/README.md @@ -1 +1 @@ -Commented notebooks with basic information, listed textbook-style. +# Commented notebooks with basic information, listed textbook-style. From 6660527d39a470f18ef6fa2278c64d890264f31d Mon Sep 17 00:00:00 2001 From: annagarbier Date: Wed, 3 Jun 2020 16:58:57 -0400 Subject: [PATCH 10/24] Update README.md --- Week_03/cheatsheets/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week_03/cheatsheets/README.md b/Week_03/cheatsheets/README.md index baea5f7..28d4f0b 100644 --- a/Week_03/cheatsheets/README.md +++ b/Week_03/cheatsheets/README.md @@ -1 +1 @@ -# Commented notebooks with basic information, listed textbook-style. +# Commented notebooks with basic information, presented textbook-style. From 09e55c8158c68936aa7bc10edd32cc4e217cf5be Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 17:16:18 -0400 Subject: [PATCH 11/24] move from scratch dir --- Week_03/class_code/palindrome_empty.ipynb | 66 +++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Week_03/class_code/palindrome_empty.ipynb diff --git a/Week_03/class_code/palindrome_empty.ipynb b/Week_03/class_code/palindrome_empty.ipynb new file mode 100644 index 0000000..dae4139 --- /dev/null +++ b/Week_03/class_code/palindrome_empty.ipynb @@ -0,0 +1,66 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Palindrome - completed code & going further\n", + "\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", + "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", + "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 +} From fa56e48d7f06f8df443a379e0d6797538ad71cae Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 17:17:34 -0400 Subject: [PATCH 12/24] add exercises --- Week_03/.DS_Store | Bin 0 -> 8196 bytes Week_03/cheatsheets/cheatsheet_strings.ipynb | 688 ++++++++++++++++++ Week_03/exercises/exercises.ipynb | 650 +++++++++++++++++ ...ome_completed_code_and_going_further.ipynb | 222 ++++++ Week_03/exercises/text_analysis.ipynb | 684 +++++++++++++++++ 5 files changed, 2244 insertions(+) create mode 100644 Week_03/.DS_Store create mode 100644 Week_03/cheatsheets/cheatsheet_strings.ipynb create mode 100644 Week_03/exercises/exercises.ipynb create mode 100644 Week_03/exercises/palindrome_completed_code_and_going_further.ipynb create mode 100644 Week_03/exercises/text_analysis.ipynb diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..aa594d4041caaf4765d1ac38746ff27be5742aa0 GIT binary patch literal 8196 zcmeHLTWl3Y82Qx(TDj)X7SalahSSn=^RVaa(r(=D*0Xy~ zZ`9PNZwAyS@e&i`g9e^Vcrhkk9+U(hBxzK5@IhaEG#X8O(tl?5G(g)J6O1J6G&BFq zf0^0&=G&eA2LQ06V6_6&0|28cB(I`ofg7YiY03<6&EerK2 z50Ej*NTwn=qofR_IaT(6Q7A?!2C8tfCxtu7R3vAVRN;Us957lLqYMS*>J*oh?tm#J z<2FVhMqoYyB6qKXoXpzIJM#Cy3UY4N_gxXBlZy)`rS}13sPBUX_U#TD<^1DR^JH|$ z$%Y_17K~_lBJc5>AJpLKa(Ez$I_u07J?2le@cvc&2Tsy z_4{b`xxSe_?$~1)zOvKzLeuf=ybN|Mn_Ny0IG*K?b@&C(3gkR#WnfIxv<$DCn%ddg zoZP-`=X7&&s=d9XIk{td+w`=?>Y7^j^_(4MgL- ze*nS_ik%9Gve!#Md|v`W)2oc`o~QH-uPxI4j*f3A9Jj5_=FkcY|nDMp_2ru7dq!0 zJFnGXv)1RCBlhg-x_WLTjJ1nJG2X}q3t8v6f)h@tH5!bEHGY+yw&*FI_AN1^B`rpS z(Ztv(q3_Jw)LOHAMfLJcn+?4$piOX-X;Ra?RoDBTr8DP&rZlbFbfe!jv$o4EjY+4r zcHI~#DkS;gNV%t0HwJV5$OvsEAf4E>kuo|Mzs8;s3m-9q@aU-RiM8wMS9diS#tET6 zU|F`s7;8*zR(z1#Z%nnQkwzDo0guyl)eWbK{-ZDfufPSk2yemra0NbsPv9%K2G`+h zxB<7|NB9|jh2P+J_yhhzh8kAkGBj`lHsVHX!Ckl?Q+NP7@G$n`F-&70p1~a2cn*hf z6vuHAr|>+!j2G}CzKWOdO?(^Q!7F$bKgG}RbNm9Y<2QIyJziOf(nr*|)Z#7bEkJ4F zZ1nP$omhyoiLQf({wL1fTqe$}ruLzgtJXJe-ny-QZ))y9?>fQTnIs9M7$TWdVun1% zJE=&NHWF*}b&FBDpNMCVGw}}a%2|V0(vVCfxS$Y|!;MWeEF+3D@p>5gV+ry!884T^ z#1nceBbM?d%DO{u(}>5sLRoj|dl=D`FO^g6Tchh7h~#1!ttp{1?cY=IJ-7@X! literal 0 HcmV?d00001 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/exercises/exercises.ipynb b/Week_03/exercises/exercises.ipynb new file mode 100644 index 0000000..5fb3692 --- /dev/null +++ b/Week_03/exercises/exercises.ipynb @@ -0,0 +1,650 @@ +{ + "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": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't bring you anything but trouble!\"\n" + ] + } + ], + "source": [ + "# Print the text.\n", + "text = '\"Don\\'t be a complete fool, Vance!\" he said harshly. \"That machine can\\'t bring you anything but trouble!\"'\n", + "print(text)\n", + "\n", + "# ---------- Expected ----------\n", + "# \"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't bring you anything but trouble!\"" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['\"Don\\'t', 'be', 'a', 'complete', 'fool,', 'Vance!\"', 'he', 'said', 'harshly.', '\"That', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']\n" + ] + } + ], + "source": [ + "# Print a list of words in the text.\n", + "print(text.split())\n", + "\n", + "# ---------- Expected ----------\n", + "# ['\"don\\'t', 'be', 'a', 'complete', 'fool,', 'vance!\"', 'he', 'said', 'harshly.', '\"that', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']" + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['\"Don\\'t', 'be', 'a', 'complete', 'fool,', 'Vance!\"', 'he', 'said', 'harshly.', '\"That', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']\n" + ] + } + ], + "source": [ + "# Print a de-duplicated list of words in the text.\n", + "deduplicated_list = []\n", + "\n", + "for word in text.split():\n", + " if word not in deduplicated_list:\n", + " deduplicated_list.append(word)\n", + "\n", + "print(deduplicated_list)\n", + "\n", + "# ---------- Expected ----------\n", + "# ['\"don\\'t', '\"that', 'a', 'anything', 'be', 'bring', 'but', \"can't\", 'complete', 'fool,', 'harshly.', 'he', 'machine', 'said', 'trouble!\"', 'vance!\"', 'you']" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "78\n" + ] + } + ], + "source": [ + "# Let's count the total number of words.\n", + "\n", + "num_words = len(text_data)\n", + "print(num_words)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\"don't be a complete fool, vance!\" he said harshly. \"that machine can't bring you anything but trouble!\"\n" + ] + } + ], + "source": [ + "# Print all of the text again, this time lowercased.\n", + "print(text.lower())\n", + "\n", + "# ---------- Expected ----------\n", + "# don't be a complete fool, vance!\" he said harshly. \"that machine can't bring you anything but trouble!\"" + ] + }, + { + "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", + "\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": 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", + "\n", + "text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", + "print(text_clean)" + ] + }, + { + "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": 87, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.3717331499312242\n", + "0.5727002967359051\n" + ] + } + ], + "source": [ + "book1 = \"\"\"\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", + "book2 = \"\"\"\n", + "The Trump administration is preparing an executive order intended to curtail the legal protections that shield social media companies from liability for what gets posted on their platforms, two senior administration officials said early Thursday.\n", + "\n", + "Such an order, which officials said was still being drafted and was subject to change, would make it easier for federal regulators to argue that companies like Facebook, Google, YouTube and Twitter are suppressing free speech when they move to suspend users or delete posts, among other examples.\n", + "\n", + "The move is almost certain to face a court challenge and is the latest salvo by President Trump in his repeated threats to crack down on online platforms. Twitter this week attached fact-checking notices to two of the president’s tweets after he made false claims about voter fraud, and Mr. Trump and his supporters have long accused social media companies of silencing conservative voices.\n", + "\n", + "White House officials said the president would sign the order later Thursday, but they declined to comment on its content. A spokesman for Twitter declined to comment.\n", + "\n", + "ADVERTISEMENT\n", + "\n", + "Continue reading the main story\n", + "Under Section 230 of the Communications Decency Act, online companies have broad immunity from liability for content created by their users.\n", + "\n", + "But the draft of the executive order, which refers to what it calls “selective censoring,” would allow the Commerce Department to try to refocus how broadly Section 230 is applied, and to let the Federal Trade Commission bulk up a tool for reporting online bias.\n", + "\n", + "Thanks for reading The Times.\n", + "Subscribe to The Times\n", + "It would also provide limitations on how federal dollars can be spent to advertise on social media platforms.\n", + "\n", + "Some of the ideas in the executive order date to a “social media summit” held last July at the White House, officials said.\n", + "\n", + "Although the law does not provide social media companies blanket protection — for instance, the companies must still comply with copyright law and remove pirated materials posted by users — it does shield them from some responsibility for their users’ posts.\n", + "\"\"\"\n", + "\n", + "printLexicalRichness(book1)\n", + "printLexicalRichness(book2)" + ] + }, + { + "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/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..4c0c6fe --- /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.\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": 118, + "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": 120, + "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/text_analysis.ipynb b/Week_03/exercises/text_analysis.ipynb new file mode 100644 index 0000000..556e151 --- /dev/null +++ b/Week_03/exercises/text_analysis.ipynb @@ -0,0 +1,684 @@ +{ + "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", + "\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", + "\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": 87, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.3717331499312242\n", + "0.5727002967359051\n" + ] + } + ], + "source": [ + "book1 = \"\"\"\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", + "book2 = \"\"\"\n", + "The Trump administration is preparing an executive order intended to curtail the legal protections that shield social media companies from liability for what gets posted on their platforms, two senior administration officials said early Thursday.\n", + "\n", + "Such an order, which officials said was still being drafted and was subject to change, would make it easier for federal regulators to argue that companies like Facebook, Google, YouTube and Twitter are suppressing free speech when they move to suspend users or delete posts, among other examples.\n", + "\n", + "The move is almost certain to face a court challenge and is the latest salvo by President Trump in his repeated threats to crack down on online platforms. Twitter this week attached fact-checking notices to two of the president’s tweets after he made false claims about voter fraud, and Mr. Trump and his supporters have long accused social media companies of silencing conservative voices.\n", + "\n", + "White House officials said the president would sign the order later Thursday, but they declined to comment on its content. A spokesman for Twitter declined to comment.\n", + "\n", + "ADVERTISEMENT\n", + "\n", + "Continue reading the main story\n", + "Under Section 230 of the Communications Decency Act, online companies have broad immunity from liability for content created by their users.\n", + "\n", + "But the draft of the executive order, which refers to what it calls “selective censoring,” would allow the Commerce Department to try to refocus how broadly Section 230 is applied, and to let the Federal Trade Commission bulk up a tool for reporting online bias.\n", + "\n", + "Thanks for reading The Times.\n", + "Subscribe to The Times\n", + "It would also provide limitations on how federal dollars can be spent to advertise on social media platforms.\n", + "\n", + "Some of the ideas in the executive order date to a “social media summit” held last July at the White House, officials said.\n", + "\n", + "Although the law does not provide social media companies blanket protection — for instance, the companies must still comply with copyright law and remove pirated materials posted by users — it does shield them from some responsibility for their users’ posts.\n", + "\"\"\"\n", + "\n", + "printLexicalRichness(book1)\n", + "printLexicalRichness(book2)" + ] + }, + { + "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 +} From b105c676463206c288e08641872dc3243ac708ba Mon Sep 17 00:00:00 2001 From: annagarbier Date: Wed, 3 Jun 2020 17:19:16 -0400 Subject: [PATCH 13/24] Create README.md --- Week_03/exercises/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 Week_03/exercises/README.md 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. From 8688417f7195c89bb212c3d739b0443cdb0109d7 Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 17:20:35 -0400 Subject: [PATCH 14/24] dir organization --- Week_03/.DS_Store | Bin 8196 -> 8196 bytes .../{exercises => class_code}/exercises.ipynb | 0 .../text_analysis.ipynb | 0 Week_03/exercises/.DS_Store | Bin 0 -> 6148 bytes 4 files changed, 0 insertions(+), 0 deletions(-) rename Week_03/{exercises => class_code}/exercises.ipynb (100%) rename Week_03/{exercises => class_code}/text_analysis.ipynb (100%) create mode 100644 Week_03/exercises/.DS_Store diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store index aa594d4041caaf4765d1ac38746ff27be5742aa0..801832ae4be971c15fa6c985e817959d6d04ca67 100644 GIT binary patch delta 18 ZcmZp1XmQvOA;`!$IY2;cbH3nIJ^(k^1%m(p delta 16 XcmZp1XmQvOAvoDzKzwt);8Z>UGJOSs diff --git a/Week_03/exercises/exercises.ipynb b/Week_03/class_code/exercises.ipynb similarity index 100% rename from Week_03/exercises/exercises.ipynb rename to Week_03/class_code/exercises.ipynb diff --git a/Week_03/exercises/text_analysis.ipynb b/Week_03/class_code/text_analysis.ipynb similarity index 100% rename from Week_03/exercises/text_analysis.ipynb rename to Week_03/class_code/text_analysis.ipynb diff --git a/Week_03/exercises/.DS_Store b/Week_03/exercises/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 Date: Wed, 3 Jun 2020 17:27:56 -0400 Subject: [PATCH 15/24] update lexical richness nbonus exercise --- Week_03/.DS_Store | Bin 8196 -> 8196 bytes Week_03/class_code/.DS_Store | Bin 0 -> 6148 bytes .../lexical_richness_scorer-checkpoint.ipynb} | 51 +- .../exercises/lexical_richness_scorer.ipynb | 663 ++++++++++++++++++ 4 files changed, 680 insertions(+), 34 deletions(-) create mode 100644 Week_03/class_code/.DS_Store rename Week_03/class_code/{text_analysis.ipynb => .ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb} (91%) create mode 100644 Week_03/exercises/lexical_richness_scorer.ipynb diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store index 801832ae4be971c15fa6c985e817959d6d04ca67..aa594d4041caaf4765d1ac38746ff27be5742aa0 100644 GIT binary patch delta 16 XcmZp1XmQvOAvoDzKzwt);8Z>UGJOSs delta 18 ZcmZp1XmQvOA;`!$IY2;cbH3nIJ^(k^1%m(p diff --git a/Week_03/class_code/.DS_Store b/Week_03/class_code/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0\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": [ - "book1 = \"\"\"\n", + "# 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", @@ -609,33 +618,7 @@ " _I fear you're fickle as a meteorite_\n", " _Though my love's constant as the Sun._\"\"\"\n", "\n", - "book2 = \"\"\"\n", - "The Trump administration is preparing an executive order intended to curtail the legal protections that shield social media companies from liability for what gets posted on their platforms, two senior administration officials said early Thursday.\n", - "\n", - "Such an order, which officials said was still being drafted and was subject to change, would make it easier for federal regulators to argue that companies like Facebook, Google, YouTube and Twitter are suppressing free speech when they move to suspend users or delete posts, among other examples.\n", - "\n", - "The move is almost certain to face a court challenge and is the latest salvo by President Trump in his repeated threats to crack down on online platforms. Twitter this week attached fact-checking notices to two of the president’s tweets after he made false claims about voter fraud, and Mr. Trump and his supporters have long accused social media companies of silencing conservative voices.\n", - "\n", - "White House officials said the president would sign the order later Thursday, but they declined to comment on its content. A spokesman for Twitter declined to comment.\n", - "\n", - "ADVERTISEMENT\n", - "\n", - "Continue reading the main story\n", - "Under Section 230 of the Communications Decency Act, online companies have broad immunity from liability for content created by their users.\n", - "\n", - "But the draft of the executive order, which refers to what it calls “selective censoring,” would allow the Commerce Department to try to refocus how broadly Section 230 is applied, and to let the Federal Trade Commission bulk up a tool for reporting online bias.\n", - "\n", - "Thanks for reading The Times.\n", - "Subscribe to The Times\n", - "It would also provide limitations on how federal dollars can be spent to advertise on social media platforms.\n", - "\n", - "Some of the ideas in the executive order date to a “social media summit” held last July at the White House, officials said.\n", - "\n", - "Although the law does not provide social media companies blanket protection — for instance, the companies must still comply with copyright law and remove pirated materials posted by users — it does shield them from some responsibility for their users’ posts.\n", - "\"\"\"\n", - "\n", - "printLexicalRichness(book1)\n", - "printLexicalRichness(book2)" + "printLexicalRichness(book)" ] }, { diff --git a/Week_03/exercises/lexical_richness_scorer.ipynb b/Week_03/exercises/lexical_richness_scorer.ipynb new file mode 100644 index 0000000..a93c2cc --- /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.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 87f9a37b3ba1603fbdbc207773a2282791ba5e91 Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 17:39:27 -0400 Subject: [PATCH 16/24] add single vs double quote blank notebook --- .../double_vs_single_quotes-checkpoint.ipynb | 39 ++ .../class_code/double_vs_single_quotes.ipynb | 39 ++ Week_03/class_code/exercises.ipynb | 650 ------------------ 3 files changed, 78 insertions(+), 650 deletions(-) create mode 100644 Week_03/class_code/.ipynb_checkpoints/double_vs_single_quotes-checkpoint.ipynb create mode 100644 Week_03/class_code/double_vs_single_quotes.ipynb delete mode 100644 Week_03/class_code/exercises.ipynb 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/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/exercises.ipynb b/Week_03/class_code/exercises.ipynb deleted file mode 100644 index 5fb3692..0000000 --- a/Week_03/class_code/exercises.ipynb +++ /dev/null @@ -1,650 +0,0 @@ -{ - "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": 20, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't bring you anything but trouble!\"\n" - ] - } - ], - "source": [ - "# Print the text.\n", - "text = '\"Don\\'t be a complete fool, Vance!\" he said harshly. \"That machine can\\'t bring you anything but trouble!\"'\n", - "print(text)\n", - "\n", - "# ---------- Expected ----------\n", - "# \"Don't be a complete fool, Vance!\" he said harshly. \"That machine can't bring you anything but trouble!\"" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['\"Don\\'t', 'be', 'a', 'complete', 'fool,', 'Vance!\"', 'he', 'said', 'harshly.', '\"That', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']\n" - ] - } - ], - "source": [ - "# Print a list of words in the text.\n", - "print(text.split())\n", - "\n", - "# ---------- Expected ----------\n", - "# ['\"don\\'t', 'be', 'a', 'complete', 'fool,', 'vance!\"', 'he', 'said', 'harshly.', '\"that', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']" - ] - }, - { - "cell_type": "code", - "execution_count": 56, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['\"Don\\'t', 'be', 'a', 'complete', 'fool,', 'Vance!\"', 'he', 'said', 'harshly.', '\"That', 'machine', \"can't\", 'bring', 'you', 'anything', 'but', 'trouble!\"']\n" - ] - } - ], - "source": [ - "# Print a de-duplicated list of words in the text.\n", - "deduplicated_list = []\n", - "\n", - "for word in text.split():\n", - " if word not in deduplicated_list:\n", - " deduplicated_list.append(word)\n", - "\n", - "print(deduplicated_list)\n", - "\n", - "# ---------- Expected ----------\n", - "# ['\"don\\'t', '\"that', 'a', 'anything', 'be', 'bring', 'but', \"can't\", 'complete', 'fool,', 'harshly.', 'he', 'machine', 'said', 'trouble!\"', 'vance!\"', 'you']" - ] - }, - { - "cell_type": "code", - "execution_count": 73, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "78\n" - ] - } - ], - "source": [ - "# Let's count the total number of words.\n", - "\n", - "num_words = len(text_data)\n", - "print(num_words)" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\"don't be a complete fool, vance!\" he said harshly. \"that machine can't bring you anything but trouble!\"\n" - ] - } - ], - "source": [ - "# Print all of the text again, this time lowercased.\n", - "print(text.lower())\n", - "\n", - "# ---------- Expected ----------\n", - "# don't be a complete fool, vance!\" he said harshly. \"that machine can't bring you anything but trouble!\"" - ] - }, - { - "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", - "\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": 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", - "\n", - "text_clean = text_lower.replace('\"', '').replace('.', '').replace('!', '').replace(',', '')\n", - "print(text_clean)" - ] - }, - { - "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": 87, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.3717331499312242\n", - "0.5727002967359051\n" - ] - } - ], - "source": [ - "book1 = \"\"\"\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", - "book2 = \"\"\"\n", - "The Trump administration is preparing an executive order intended to curtail the legal protections that shield social media companies from liability for what gets posted on their platforms, two senior administration officials said early Thursday.\n", - "\n", - "Such an order, which officials said was still being drafted and was subject to change, would make it easier for federal regulators to argue that companies like Facebook, Google, YouTube and Twitter are suppressing free speech when they move to suspend users or delete posts, among other examples.\n", - "\n", - "The move is almost certain to face a court challenge and is the latest salvo by President Trump in his repeated threats to crack down on online platforms. Twitter this week attached fact-checking notices to two of the president’s tweets after he made false claims about voter fraud, and Mr. Trump and his supporters have long accused social media companies of silencing conservative voices.\n", - "\n", - "White House officials said the president would sign the order later Thursday, but they declined to comment on its content. A spokesman for Twitter declined to comment.\n", - "\n", - "ADVERTISEMENT\n", - "\n", - "Continue reading the main story\n", - "Under Section 230 of the Communications Decency Act, online companies have broad immunity from liability for content created by their users.\n", - "\n", - "But the draft of the executive order, which refers to what it calls “selective censoring,” would allow the Commerce Department to try to refocus how broadly Section 230 is applied, and to let the Federal Trade Commission bulk up a tool for reporting online bias.\n", - "\n", - "Thanks for reading The Times.\n", - "Subscribe to The Times\n", - "It would also provide limitations on how federal dollars can be spent to advertise on social media platforms.\n", - "\n", - "Some of the ideas in the executive order date to a “social media summit” held last July at the White House, officials said.\n", - "\n", - "Although the law does not provide social media companies blanket protection — for instance, the companies must still comply with copyright law and remove pirated materials posted by users — it does shield them from some responsibility for their users’ posts.\n", - "\"\"\"\n", - "\n", - "printLexicalRichness(book1)\n", - "printLexicalRichness(book2)" - ] - }, - { - "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 -} From 0927ee1cf70d071d79e2fa6019fe695057e8e291 Mon Sep 17 00:00:00 2001 From: Anna Date: Wed, 3 Jun 2020 18:09:58 -0400 Subject: [PATCH 17/24] live code updates --- .../palindrome_empty-checkpoint.ipynb | 79 +++++++ Week_03/class_code/palindrome_empty.ipynb | 30 ++- ...ed_code_and_going_further-checkpoint.ipynb | 222 ++++++++++++++++++ ...ome_completed_code_and_going_further.ipynb | 6 +- 4 files changed, 326 insertions(+), 11 deletions(-) create mode 100644 Week_03/class_code/.ipynb_checkpoints/palindrome_empty-checkpoint.ipynb create mode 100644 Week_03/exercises/.ipynb_checkpoints/palindrome_completed_code_and_going_further-checkpoint.ipynb 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/palindrome_empty.ipynb b/Week_03/class_code/palindrome_empty.ipynb index dae4139..5239bc0 100644 --- a/Week_03/class_code/palindrome_empty.ipynb +++ b/Week_03/class_code/palindrome_empty.ipynb @@ -4,18 +4,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Palindrome - completed code & going further\n", + "# Palindrome - live code\n", "\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", - "We are going to create a function that checks whether or not a given phrase is a palindrome. Here are our guidelines:\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 **return** either True (if `txt` is a palindrome) or `False` (if `txt`\n", - " is not a palindrome).\n", - " \n", + "* It will print True if `txt` is a palindrome or `False` if `txt`\n", + " is not a palindrome.\n", "\n", - "We will use the following test cases to check our function:\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", @@ -39,7 +49,11 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "# wow --> wow\n", + "# Anna --> \n", + "# race car --> " + ] } ], "metadata": { 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/palindrome_completed_code_and_going_further.ipynb b/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb index 4c0c6fe..f3fbcdd 100644 --- a/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb +++ b/Week_03/exercises/palindrome_completed_code_and_going_further.ipynb @@ -48,7 +48,7 @@ "\n", "## Recommended for evereyone:\n", "\n", - "- Below is the code we wrote in class together.\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", @@ -58,7 +58,7 @@ }, { "cell_type": "code", - "execution_count": 118, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -130,7 +130,7 @@ }, { "cell_type": "code", - "execution_count": 120, + "execution_count": 2, "metadata": {}, "outputs": [ { From ed438213b1f5dac26b90c7b11dad8b8f494ed152 Mon Sep 17 00:00:00 2001 From: Lan Zhang Date: Wed, 3 Jun 2020 18:23:05 -0400 Subject: [PATCH 18/24] update wk3 --- .DS_Store | Bin 14340 -> 14340 bytes .../class_code/madlibs_event_invitation.ipynb | 87 ++++++---- .../madlibs_event_invitation_empty.ipynb | 22 +-- .../exercises/Madlibs_exercise_answers.ipynb | 157 ++++++++++++++++++ 4 files changed, 226 insertions(+), 40 deletions(-) create mode 100644 Week_03/exercises/Madlibs_exercise_answers.ipynb diff --git a/.DS_Store b/.DS_Store index 7372fdb1364db339870ba236b7cb04b4ab2b3410..f58d639b5f98da2a3f5fc6cd251300381618dd45 100644 GIT binary patch delta 77 zcmZoEXeromT$PQJgOh`oV{)TNk`Rc=880AFU2S4)prc@HY`NJ{t&N|clEaJuvb+%( delta 25 bcmZoEXeromTy?UY*vZWk)Xe#zj1oowlBo)E diff --git a/Week_03/class_code/madlibs_event_invitation.ipynb b/Week_03/class_code/madlibs_event_invitation.ipynb index e228be5..2a26a2a 100644 --- a/Week_03/class_code/madlibs_event_invitation.ipynb +++ b/Week_03/class_code/madlibs_event_invitation.ipynb @@ -4,21 +4,46 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# A Mad-Lib style generator\n", + "# 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", + "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 template that would allow us to automate copies of invitations" + "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": 1, + "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", @@ -27,20 +52,9 @@ " def getAll(li):\n", " return ', '.join(li[:-1]) + \", and %s\" %(li[-1])\n", " \n", - " # format guestnames\n", - " def formatnames(namelist):\n", - " guest_list = []\n", - " for name in namelist:\n", - " if len(name) == 1:\n", - " guest_list.append(name[0])\n", - " elif len(name) == 2:\n", - " guest_list.append(' and '.join(name))\n", - " else:\n", - " guest_list.append(getAll(name))\n", - " return guest_list\n", - " \n", + " \n", " # variables needed:\n", - " guestlist = formatnames(namelist)\n", + " guestlist = namelist\n", " type_of_event = event_type\n", " date = date[::-1]\n", " location = loc[::-1] # a simple reversed encrption\n", @@ -56,6 +70,8 @@ " ---\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", @@ -67,7 +83,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -85,7 +101,17 @@ " ---\n", " \n", "\n", - " Hey Mary and guest:\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", @@ -95,7 +121,7 @@ " ---\n", " \n", "\n", - " Hey Lan, Anna, Jason, and Sven:\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", @@ -105,7 +131,17 @@ " ---\n", " \n", "\n", - " Hey Friends and Family:\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", @@ -118,19 +154,12 @@ } ], "source": [ - "guests = ((\"Bob\",),(\"Mary\",\"guest\"),(\"Lan\",\"Anna\",\"Jason\",\"Sven\"),('Friends','Family'));\n", + "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)" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { diff --git a/Week_03/class_code/madlibs_event_invitation_empty.ipynb b/Week_03/class_code/madlibs_event_invitation_empty.ipynb index 98f28ce..f4d79c2 100644 --- a/Week_03/class_code/madlibs_event_invitation_empty.ipynb +++ b/Week_03/class_code/madlibs_event_invitation_empty.ipynb @@ -4,15 +4,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# A Mad-Lib style generator\n", + "# 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", + "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 copies of event invitations.\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", + " Hey, _guestname_!\n", " You are invited to a _type_of_event_! Join us on _date_ at _location_!\n", " Bring _items_.\n", " \n", @@ -23,7 +23,7 @@ "\n", "An example output:\n", "```\n", - " Hey Lan, Anna, Jason, and Sven:\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", @@ -34,7 +34,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "metadata": {}, "outputs": [], "source": [ @@ -43,7 +43,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 40, "metadata": {}, "outputs": [], "source": [ @@ -52,7 +52,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 66, "metadata": {}, "outputs": [], "source": [ @@ -62,7 +62,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 67, "metadata": {}, "outputs": [], "source": [ @@ -71,7 +71,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 68, "metadata": {}, "outputs": [], "source": [ @@ -80,7 +80,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 64, "metadata": {}, "outputs": [], "source": [ 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 +} From 0a48a78a28008eec6315901838deecc646248878 Mon Sep 17 00:00:00 2001 From: ssleung11 <42116150+ssleung11@users.noreply.github.com> Date: Wed, 3 Jun 2020 18:40:15 -0400 Subject: [PATCH 19/24] Update README.md --- Week_03/README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Week_03/README.md b/Week_03/README.md index fcc9f8b..c627484 100644 --- a/Week_03/README.md +++ b/Week_03/README.md @@ -1 +1,13 @@ ## Week III: Strings, Lists, and Tuples + +--- +#### Topics +* Tuples, Functions +* String + List +* Extra: Python Bot + Raspberry Pi + + +--- + +#### Link to slides +https://docs.google.com/presentation/d/1LOffhetydFlmyiC7BpUwCTuRlyk_CGCLf1qmzvhi6eM/edit?usp=sharing From 4a8d045429740a48465c7b28c480a93478d4173a Mon Sep 17 00:00:00 2001 From: Lan Zhang Date: Wed, 3 Jun 2020 21:38:49 -0400 Subject: [PATCH 20/24] add inclass --- .DS_Store | Bin 14340 -> 14340 bytes Week_03/.DS_Store | Bin 8196 -> 6148 bytes .../[in_class]madlibs_invitation.ipynb | 327 ++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 Week_03/class_code/[in_class]madlibs_invitation.ipynb diff --git a/.DS_Store b/.DS_Store index f58d639b5f98da2a3f5fc6cd251300381618dd45..c3c8bd533c87e8447c003c434e032fb67336726c 100644 GIT binary patch delta 35 gcmZoEXeroWsm5V!Y^tMRY;3UEQSApmGVd@W0KPE_0RR91 delta 35 gcmZoEXeroWsm5VqY@nlHY;3vNQSApmGVd@W0KSh33jhEB diff --git a/Week_03/.DS_Store b/Week_03/.DS_Store index aa594d4041caaf4765d1ac38746ff27be5742aa0..9e15f5a9149245e3635406340f2f4b1516933345 100644 GIT binary patch delta 203 zcmZp1XfcprU|?W$DortDU=RQ@Ie-{MGjUEV6q~50D9Qwq2a6Rm#4{u_Qx(TDj)X7SalahSSn=^RVaa(r(=D*0Xy~ zZ`9PNZwAyS@e&i`g9e^Vcrhkk9+U(hBxzK5@IhaEG#X8O(tl?5G(g)J6O1J6G&BFq zf0^0&=G&eA2LQ06V6_6&0|28cB(I`ofg7YiY03<6&EerK2 z50Ej*NTwn=qofR_IaT(6Q7A?!2C8tfCxtu7R3vAVRN;Us957lLqYMS*>J*oh?tm#J z<2FVhMqoYyB6qKXoXpzIJM#Cy3UY4N_gxXBlZy)`rS}13sPBUX_U#TD<^1DR^JH|$ z$%Y_17K~_lBJc5>AJpLKa(Ez$I_u07J?2le@cvc&2Tsy z_4{b`xxSe_?$~1)zOvKzLeuf=ybN|Mn_Ny0IG*K?b@&C(3gkR#WnfIxv<$DCn%ddg zoZP-`=X7&&s=d9XIk{td+w`=?>Y7^j^_(4MgL- ze*nS_ik%9Gve!#Md|v`W)2oc`o~QH-uPxI4j*f3A9Jj5_=FkcY|nDMp_2ru7dq!0 zJFnGXv)1RCBlhg-x_WLTjJ1nJG2X}q3t8v6f)h@tH5!bEHGY+yw&*FI_AN1^B`rpS z(Ztv(q3_Jw)LOHAMfLJcn+?4$piOX-X;Ra?RoDBTr8DP&rZlbFbfe!jv$o4EjY+4r zcHI~#DkS;gNV%t0HwJV5$OvsEAf4E>kuo|Mzs8;s3m-9q@aU-RiM8wMS9diS#tET6 zU|F`s7;8*zR(z1#Z%nnQkwzDo0guyl)eWbK{-ZDfufPSk2yemra0NbsPv9%K2G`+h zxB<7|NB9|jh2P+J_yhhzh8kAkGBj`lHsVHX!Ckl?Q+NP7@G$n`F-&70p1~a2cn*hf z6vuHAr|>+!j2G}CzKWOdO?(^Q!7F$bKgG}RbNm9Y<2QIyJziOf(nr*|)Z#7bEkJ4F zZ1nP$omhyoiLQf({wL1fTqe$}ruLzgtJXJe-ny-QZ))y9?>fQTnIs9M7$TWdVun1% zJE=&NHWF*}b&FBDpNMCVGw}}a%2|V0(vVCfxS$Y|!;MWeEF+3D@p>5gV+ry!884T^ z#1nceBbM?d%DO{u(}>5sLRoj|dl=D`FO^g6Tchh7h~#1!ttp{1?cY=IJ-7@X! 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 +} From 489594b117703aaa70429ba5d7936a87dbccdd06 Mon Sep 17 00:00:00 2001 From: Lan Zhang <42923290+lanzhang76@users.noreply.github.com> Date: Wed, 3 Jun 2020 21:51:18 -0400 Subject: [PATCH 21/24] Update README.md --- Week_03/README.md | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/Week_03/README.md b/Week_03/README.md index c627484..b0ba891 100644 --- a/Week_03/README.md +++ b/Week_03/README.md @@ -1,13 +1,35 @@ ## Week III: Strings, Lists, and Tuples ---- #### Topics -* Tuples, Functions -* String + List -* Extra: Python Bot + Raspberry Pi +- 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 + - Mad Libs generator +- [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!` + +#### +Google slides: +- [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) --- #### Link to slides -https://docs.google.com/presentation/d/1LOffhetydFlmyiC7BpUwCTuRlyk_CGCLf1qmzvhi6eM/edit?usp=sharing +[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) From 8b8eb2f4342d2e15339dfcc059f84d1b1682f7c7 Mon Sep 17 00:00:00 2001 From: Lan Zhang <42923290+lanzhang76@users.noreply.github.com> Date: Wed, 3 Jun 2020 21:51:29 -0400 Subject: [PATCH 22/24] Update README.md From 0d575a2b31dd060a552b36157001924c141f2702 Mon Sep 17 00:00:00 2001 From: Lan Zhang <42923290+lanzhang76@users.noreply.github.com> Date: Wed, 3 Jun 2020 21:56:51 -0400 Subject: [PATCH 23/24] Update README.md --- Week_03/README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Week_03/README.md b/Week_03/README.md index b0ba891..aa4a96e 100644 --- a/Week_03/README.md +++ b/Week_03/README.md @@ -5,6 +5,7 @@ - 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) @@ -13,21 +14,24 @@ - [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!` +--- -#### -Google slides: +#### 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) + --- -#### Link to slides +#### class slides [Week3 google slide](https://docs.google.com/presentation/d/1LOffhetydFlmyiC7BpUwCTuRlyk_CGCLf1qmzvhi6eM/edit?usp=sharing) From 23b75b4b09523dae6b3ddf2d58b0906a8c8248fb Mon Sep 17 00:00:00 2001 From: Lan Zhang Date: Thu, 4 Jun 2020 09:56:02 -0400 Subject: [PATCH 24/24] clean --- .../lexical_richness_scorer-checkpoint.ipynb | 663 ++++++++++++++++++ .../exercises/lexical_richness_scorer.ipynb | 2 +- 2 files changed, 664 insertions(+), 1 deletion(-) create mode 100644 Week_03/exercises/.ipynb_checkpoints/lexical_richness_scorer-checkpoint.ipynb 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/lexical_richness_scorer.ipynb b/Week_03/exercises/lexical_richness_scorer.ipynb index a93c2cc..e165632 100644 --- a/Week_03/exercises/lexical_richness_scorer.ipynb +++ b/Week_03/exercises/lexical_richness_scorer.ipynb @@ -655,7 +655,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.6" + "version": "3.7.4" } }, "nbformat": 4,