{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "

Mathematics and Computing
Logic And Algorithms

Spring 2018

\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "## Comparisons and Decisions\n", "\n", "Algorithms are problem-solving techniques via a sequence of steps of the following form:\n", "\n", "* Each step changes inputs to outputs (statements)\n", "* A subsequence of steps may be repeated (loops)\n", "* A decision point may lead to one of two different subsequences of steps (branches)\n", "\n", "We introduced statements and loops in the previous notebook, so in this notebook we focus on _branches_ (i.e., decisions), which means we need to explore how logic is implemented in Python. \n", "\n", "To begin with, a __BooleanStatement__ is a statement which evaluates as either __True__ or __False__. Typically, a __BooleanStatement__ is produced by a _logical comparison_. \n", "\n", "For example, let's look at some examples of logical comparisons. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": { }, "output_type": "execute_result" } ], "source": [ "2 > 1" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 10, "metadata": { }, "output_type": "execute_result" } ], "source": [ "x = 5 \n", "\n", "0 < x <= 7" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 11, "metadata": { }, "output_type": "execute_result" } ], "source": [ "x != 5" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": { }, "output_type": "execute_result" } ], "source": [ "3 in range(0,7)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 5, "metadata": { }, "output_type": "execute_result" } ], "source": [ "10 in range(0,7)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Equality is also an important concept, but one which is __NOT__ defined clearly enough in mathematics. Indeed, in Python, there are 3 ways that equality occurs, only 2 of which are logical. \n", "\n", "* __Assignment:__ Python uses a single equals to bind a _name_ to an object. ASSIGNMENT (single equals) IS NOT LOGICAL. \n", "* __Equal Value:__ Python uses __==__ to logically test if two objects have the same value.\n", "* __Identical Objects:__ Python uses the word __is__ to test if two objects are identical. \n", "\n", "Giving an object a name (mathematically, assigning a value to a variable) does not produce __True__ or __False__, so it cannot be used to make decisions. \n", "\n", "Let's look at examples of all 3. " ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ "x = 2.0 # error because numbers cannot be used as variable names" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 7, "metadata": { }, "output_type": "execute_result" } ], "source": [ "2 == 2.0 # These numbers have the same value" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 10, "metadata": { }, "output_type": "execute_result" } ], "source": [ "2 is 2.0 # 2 is an integer, while 2.0 is a decimal (i.e., float)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "For example, suppose we want to determine if an integer is either even or odd. A even number has a remainder of 0 if divided by 2, so that \n", "\n", "n % 2 is zero if n is even\n", "\n", "This is easily implemented as a __BooleanStatement__." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 11, "metadata": { }, "output_type": "execute_result" } ], "source": [ "n = 7 \n", "\n", "n % 2 == 0 " ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 12, "metadata": { }, "output_type": "execute_result" } ], "source": [ "n = 12 \n", "\n", "n % 2 == 0 " ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "All logical comparisons are __BooleanStatement__s, but __BooleanStatement__s can be produced in many, many, many other ways. \n", "\n", "We can't possible explore all possible ways, so instead, let's focus on the __numpy__ library for arrays and on the _logic_ associated with mathematical structures like matrices. \n", "\n", "First, we execute the usual import/plot configuration structures: " ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "\n", "import numpy as np" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "The names __np__ and __plt__ are conventional and are used because they are short and easy to remember. \n", "\n", "Moreover, both __numpy__ and __matplotlib__ have commands that are __BooleanStatements__. " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 14, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.iscomplex(1+1j)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 15, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.iscomplex(3)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 16, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.iterable([1,2,3])" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 17, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.iterable( 5 )" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 18, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.isreal(5)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 19, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.isreal(5+1j)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 20, "metadata": { }, "output_type": "execute_result" } ], "source": [ "plt.is_numlike( 1 )" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 21, "metadata": { }, "output_type": "execute_result" } ], "source": [ "plt.is_numlike(\"Hi Mom!\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 22, "metadata": { }, "output_type": "execute_result" } ], "source": [ "plt.fignum_exists(12)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Indeed, almost every module includes __BooleanStatement__ commands needed in that module. \n", "\n", "__BooleanStatement__s can be used to form __compound__ comparisons using __and__, __not__, and __or__. A compound condition is a logical combination of one or more __BooleanStatement__s A and B according to the following: \n", "\n", "* A __and__ B evalues to __True__ only if A and B both evaluate to __True__. Otherwise, evaluates __False__. \n", "* __not A__ evaluates to __True__ if A evaluates to __False__, and vice versa. \n", "* A __or__ B evaluates to __True__ if either of A or B are __True__, but is __False__ if both A and B evaluate __False__.\n", "\n", "Let's look at some examples. " ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 23, "metadata": { }, "output_type": "execute_result" } ], "source": [ "x = 5 \n", "\n", "x > 7 and np.isreal(x)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": { }, "output_type": "execute_result" } ], "source": [ "x > 7 or np.isreal(x)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 25, "metadata": { }, "output_type": "execute_result" } ], "source": [ "not x > 7 " ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Indeed, compound statements are potentially quite long and complicated. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": { }, "output_type": "execute_result" } ], "source": [ "a, b, c, d = 3, 7, 9, 11\n", "\n", "(a > b ) or ( not ( b == c + d and np.isreal( b*c ) ) or ( a+d <= b + c) )" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 27, "metadata": { }, "output_type": "execute_result" } ], "source": [ "( ( b in range(a,c) ) or ( a+d <= b*c <= a*d ) ) and ( not (a + d < b + c) or (a*c > b*d ))" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "## Decision Making in Algorithms \n", "\n", "In Python, the simplest form for a branching structure (i.e., a decision structure) is \n", "\n", "```python\n", "if BooleanStatement : \n", " Statement1_if_True\n", " Statement2_if_True\n", " ...\n", "Statement1_not_inBranchingStructure\n", "...\n", "```\n", "The statements in the __if__ structure are executed only if the __BooleanStatement__ evaluates to __True__. " ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n is even\n" ] } ], "source": [ "n = 8 \n", "\n", "if( n % 2 == 0 ):\n", " print('n is even')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Decision structures (if statements) allow us to implement algorithms in which the sequence of steps depends on the initial input. \n", "\n", "For example, the algorithm for _Making Change_ is straightforward. A customer pays at least the price of a product to a cashier, who subsequently __return__s the difference in the form of dollars, quarters, dimes, nickels, and pennies. \n", "\n", "The logic for this algorithm is implemented as a series of if statements in the next cell. Try changing the price and the amount paid to see how the logic varies according to the initial inputs. " ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Change is \n", "3 dollars and \n", "2 quarters and \n", "1 dimes and \n", "4 pennies\n" ] } ], "source": [ "Price = 1.36\n", "AmountPaid = 5.00 \n", "\n", "assert AmountPaid >= Price, \"Must pay at least the price\"\n", "\n", "Return = AmountPaid - Price\n", "\n", "print(\"Change is \")\n", "if( Return / 1 >= 1 ): \n", " NumDollars = int( Return/1 )\n", " print(\"{0} dollars and \".format(NumDollars))\n", " Return = Return - NumDollars*1\n", "if( Return / 0.25 >= 1 ):\n", " NumQuarters = int(Return/0.25)\n", " print(\"{0} quarters and \".format(NumQuarters))\n", " Return = Return - NumQuarters*0.25\n", "if( Return / 0.10 >= 1 ):\n", " NumDimes = int(Return/0.10)\n", " print(\"{0} dimes and \".format(NumDimes))\n", " Return = Return - NumDimes*0.10\n", "if( Return / 0.05 >= 1 ):\n", " NumNickels = int(Return/0.25)\n", " print(\"{0} nickels and \".format(NumNickels))\n", " Return = Return - NumNickels*0.05\n", "print(\"{0} pennies\".format( round(100*Return) ) )" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "An __else__ structure can be added for the case where a __BooleanStatement__ is __False__: \n", "\n", "```python\n", "if BooleanStatement : \n", " Statement1_if_True\n", " Statement2_if_True\n", " ...\n", "else:\n", " Statement1_if_False\n", " Statement2_if_False\n", " ...\n", "Statement1_not_inBranchingStructure\n", "...\n", "```\n", "Let's look at an example. " ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n is odd\n" ] } ], "source": [ "n = 7 \n", "\n", "if( n % 2 == 0 ):\n", " print('n is even')\n", "else:\n", " print('n is odd')" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We can also include an unlimited number of __elif__ structures, which test a new __BooleanStatement1__ for the case where the original __BooleanStatement__ is __False__: \n", "\n", "```python\n", "if BooleanStatement : \n", " Statement1_if_True\n", " Statement2_if_True\n", " ...\n", "elif BooleanStatement1:\n", " Statement1_if_BS1_True\n", " Statement2_if_BS1_True\n", " ...\n", "else:\n", " Statement1_if_BS_and_BS1_both_False\n", " Statement2_if_BS_and_BS1_both_False\n", " ...\n", "Statement1_not_inBranchingStructure\n", "...\n", "```\n", "Let's look at an example. " ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3 is a factor of 15\n" ] } ], "source": [ "x = 15 \n", "\n", "if( x % 2 == 0 ):\n", " print( '2 is a factor of {0}'.format(x) )\n", "elif( x % 3 == 0 ):\n", " print( '3 is a factor of {0}'.format(x) )\n", "elif( x % 4 == 0 ):\n", " print( '4 is a factor of {0}'.format(x) )\n", "else:\n", " print( '{0} is not divisible by 2, 3, or 4.'.format(x) )\n", " " ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Typically, these decision structures are combined with loops and other structures in implementing algorithms. \n", "\n", "For example, the loop below tests if a given integer __x__ is prime. " ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'817 is divisible by 19'" ] }, "execution_count": 32, "metadata": { }, "output_type": "execute_result" } ], "source": [ "x = 817\n", "\n", "message = \"{0} is prime\".format(x) \n", "for p in range(2,x): # actually only need to go to x//2 \n", " if( x % p == 0 ):\n", " message = \"{0} is divisible by {1}\".format(x,p)\n", " break # ends the loop\n", "message" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Moreover, we can loop over any list or tuple or any other iterable -- such as a numpy array. \n", "\n", "In this case, we can use logic and decisions to _count_ or otherwise analyze what is in a __list__ or numpy __array__. \n", "\n", "For example, if create a long numpy __array__ of random integers -- using the __randint__ command -- then we can loop over that array and use a decision statement to _count_ the number of occurences of a given pattern. " ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([2, 2, 2, ..., 3, 4, 1])" ] }, "execution_count": 33, "metadata": { }, "output_type": "execute_result" } ], "source": [ "from numpy.random import randint\n", "\n", "RollsOfADie = randint(1,7,10000) # 10,000 simulated rolls of a fair die\n", "RollsOfADie" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4967" ] }, "execution_count": 34, "metadata": { }, "output_type": "execute_result" } ], "source": [ "cnt = 0 # count starts at 0\n", "\n", "for roll in RollsOfADie:\n", " if( roll % 2 == 0 ): # if roll is even\n", " cnt += 1\n", "cnt ## should be about 1/2 of the 10,000 rolls" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Of course, this is a simple example. But how about the question like \"how many times is the current roll equal to the previous roll\"? " ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1572" ] }, "execution_count": 35, "metadata": { }, "output_type": "execute_result" } ], "source": [ "cnt = 0 # count starts at 0\n", "\n", "prevRoll = 0 # to guarantee we don't count the first roll \n", "for roll in RollsOfADie:\n", " if( roll == prevRoll ): # if roll is even\n", " cnt += 1\n", " prevRoll = roll\n", "cnt " ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Indeed, many interesting mathematical questions can be answered in much the same way. \n", "\n", "

 

\n", "\n", "## Logic with Lists and Dictionaries \n", "\n", "Python allows the use of logic and decisions in many useful ways and in many useful contexts. For example, __list comprehension__ is the creation of a list using the structure\n", "\n", "```python\n", " [ FunctionOfValue for Value in Iterable if BooleanStatement ]\n", "```\n", "\n", "Let's look at an example. " ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "execution_count": 36, "metadata": { }, "output_type": "execute_result" } ], "source": [ "## First 10 squared positive integers \n", "[n**2 for n in range(1,11) ]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Indeed, suppose we wanted to create a __numpy array__ of numbers between 1 and 100 that do __not__ have a factor of 7. This turns out to be quite easy using list comprehension inside of the __array__ command in numpy. " ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15,\n", " 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 29, 30,\n", " 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 43, 44, 45,\n", " 46, 47, 48, 50, 51, 52, 53, 54, 55, 57, 58, 59, 60,\n", " 61, 62, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75,\n", " 76, 78, 79, 80, 81, 82, 83, 85, 86, 87, 88, 89, 90,\n", " 92, 93, 94, 95, 96, 97, 99, 100])" ] }, "execution_count": 37, "metadata": { }, "output_type": "execute_result" } ], "source": [ "np.array( [n for n in range(1,101) if n % 7 != 0 ] )" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Finally, there is a very useful structure for writing algorithms called a __dictionary__, where a __dictionary__ is a __set__ of __key, value__ pairs. \n", "\n", "We can create dictionaries in many ways in Python, but the method we use most often is as a set of key-value pairs: \n", "```python \n", "# the following is a dictionary in Python\n", "ADictionary = { 'key1':value1, 'key2':value2, ..., 'keyn':valuen } \n", "``` \n", "\n", "The __dict__ command can also be used to create dictionaries. " ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'firstlight': 7, 'midnight': 0, 'noon': 12, 'sundown': 19}" ] }, "execution_count": 38, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours = { 'noon': 12, 'midnight': 0, 'firstlight': 7, 'sundown':19 }\n", "SpecialHours" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Because a dictionary is a _set_ of key-value pairs, the order in which they are stored is not preserved (i.e., Python decides). \n", "\n", "However, we can access values using keys. " ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 39, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours['midnight']" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 40, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours['noon']" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'firstlight': 7, 'midnight': 0, 'noon': 12, 'sundown': 19, 'workStarts': 8}" ] }, "execution_count": 41, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours['workStarts'] = 8\n", "SpecialHours" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Once a dictionary is created, we can access its keys with the __keys__ command; and we can get its values using the __values__ command. " ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_keys(['firstlight', 'midnight', 'noon', 'workStarts', 'sundown'])" ] }, "execution_count": 43, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours.keys()" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_values([7, 0, 12, 8, 19])" ] }, "execution_count": 44, "metadata": { }, "output_type": "execute_result" } ], "source": [ "SpecialHours.values()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "If we loop over a dictionary, then we are getting the __keys__ one at a time: " ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "firstlight 7\n", "midnight 0\n", "noon 12\n", "workStarts 8\n", "sundown 19\n" ] } ], "source": [ "for key in SpecialHours:\n", " print(key, SpecialHours[key] )" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Dictionaries can be very useful when logic is involved when designing algorithms. \n", "\n", "For example, let's consider how a dictionary can greatly \"clean up\" the code for the _Making Change_ example, which we repeat below: " ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Change is \n", "3 dollars and \n", "2 quarters and \n", "1 dimes and \n", "4 pennies\n" ] } ], "source": [ "Price = 1.36\n", "AmountPaid = 5.00 \n", "\n", "assert AmountPaid >= Price, \"Must pay at least the price\"\n", "\n", "Return = AmountPaid - Price\n", "\n", "print(\"Change is \")\n", "if( Return / 1 >= 1 ): \n", " NumDollars = int( Return/1 )\n", " print(\"{0} dollars and \".format(NumDollars))\n", " Return = Return - NumDollars*1\n", "if( Return / 0.25 >= 1 ):\n", " NumQuarters = int(Return/0.25)\n", " print(\"{0} quarters and \".format(NumQuarters))\n", " Return = Return - NumQuarters*0.25\n", "if( Return / 0.10 >= 1 ):\n", " NumDimes = int(Return/0.10)\n", " print(\"{0} dimes and \".format(NumDimes))\n", " Return = Return - NumDimes*0.10\n", "if( Return / 0.05 >= 1 ):\n", " NumNickels = int(Return/0.25)\n", " print(\"{0} nickels and \".format(NumNickels))\n", " Return = Return - NumNickels*0.05\n", "print(\"{0} pennies\".format( round(100*Return) ) )" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Notice that we are repeating the same \"if\" statement several times, each time for a different type of coin (assuming dollar coins!). So first off, let's create a coin dictionary whose keys are the coin names and whose values are the coin values. " ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'dime': 0.1, 'dollar': 1, 'nickel': 0.05, 'quarter': 0.25}" ] }, "execution_count": 48, "metadata": { }, "output_type": "execute_result" } ], "source": [ "CoinDictionary = { 'dollar':1, 'quarter':0.25, 'dime':0.10, 'nickel':0.05 }\n", "CoinDictionary" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "Once we need to make change, we can simply loop over a list of coin names in the order they need to be considered. " ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Change is \n", "3 dollars and \n", "2 quarters and \n", "1 dimes and \n", "4 pennies\n" ] } ], "source": [ "Price = 1.36\n", "AmountPaid = 5.00 \n", "\n", "assert AmountPaid >= Price, \"Must pay at least the price\"\n", "\n", "Return = AmountPaid - Price\n", "\n", "print(\"Change is \")\n", "for coinName in ['dollar','quarter','dime','nickel']:\n", " coinValue = CoinDictionary[coinName]\n", " if( Return / coinValue >= 1 ): \n", " NumCoins = int( Return/coinValue )\n", " print(\"{0} {1}s and \".format(NumCoins, coinName) )\n", " Return = Return - NumCoins*coinValue\n", "print(\"{0} pennies\".format( round(100*Return) ) )" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "

 

\n", "\n", "## Assignment 3\n", "\n", "In the exercises below, $a,b,c,d$ are the last 4 __ _nonzero_ __ digits of your student number in _nondescending order_ ( $a \\le b \\le c \\le d$ ). Also, __EnumberLast3NonzeroDigits__ is the last 3 nonzero digits of your Enumber. For example, if your enumber was E12375609, then \n", "$$ a = 5, \\quad b = 6, \\quad c = 7, \\quad \\mathrm{and} \\quad d = 9$$ \n", "and __EnumberLast3NonzeroDigits__ is 569. \n", "\n", "__1.__ (0.25 points) Execute the following and describe in the Raw NBconvert cell what list it produced. \n", "```python \n", "list(range(c+d, a, -1) )\n", "```" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6]" ] }, "execution_count": 7, "metadata": { }, "output_type": "execute_result" } ], "source": [ "a,b,c,d=5,6,7,9\n", "list (range(c+d, a, -1))" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "The output does describes a list of eleven positive integers all in order with a range between [6 and 16] starting at 16 and ending at 6." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__2.__ (0.25 points) Execute the following and describe in the Raw NBconvert cell what list it produced. \n", "```python \n", "[n**2 for n in range(b+c, a, -1) if n % 2 == 1 ]\n", "```" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[169, 121, 81, 49]" ] }, "execution_count": 8, "metadata": { }, "output_type": "execute_result" } ], "source": [ "a,b,c,d=5,6,7,9\n", "[n**2 for n in range (b+c, a, -1) if n % 2 ==1 ]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "A list of four positive integers which represent the squared product of four odd numbers [13,11,9,7]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__3.__ (0.5 points) Determine if the following __BooleanStatement__ is __True__ or __False__ for your values of _a,b,c,d_. \n", "\"Embedded" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'a=5', 'b=6', 'c=7', 'd=9'}" ] }, "execution_count": 8, "metadata": { }, "output_type": "execute_result" } ], "source": [ "Integers={\"a=5\", \"b=6\", \"c=7\", \"d=9\"}\n", "Integers\n", "\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 15, "metadata": { }, "output_type": "execute_result" } ], "source": [ "a,b,c,d=5,6,7,9\n", "import numpy as np\n", "( (a + d < b + c ) or (a*d - b*c > 0 ) ) and not np.iscomplex((a*d - b*c)**(0.5))" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__4.__ (0.5 point) Use list comprehension to create the list of numbers between __a__ and __c\\*d__ which are __not__ divisible by __b__. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'a=5', 'b=6', 'c=7', 'd=9'}" ] }, "execution_count": 1, "metadata": { }, "output_type": "execute_result" } ], "source": [ "Integers={\"a=5\", \"b=6\", \"c=7\", \"d=9\"}\n", "Integers\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 25,\n", " 26, 27, 28, 29, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 43, 44, 45,\n", " 46, 47, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59, 61, 62])" ] }, "execution_count": 4, "metadata": { }, "output_type": "execute_result" } ], "source": [ "a,b,c,d=5,6,7,9\n", "import numpy as np\n", "np.array( [n for n in range(a,c*d) if n % b != 0 ] )" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__5.__ (0.5 points) Create a dictionary in which the keys are the first names of 5 people you know and the values are their ages, respectively. " ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'Charlie': 26, 'Chloe': 18, 'Jack': 34, 'Megan': 23, 'Tom': 36}" ] }, "execution_count": 63, "metadata": { }, "output_type": "execute_result" } ], "source": [ "Adictionary={'Jack':34, 'Tom':36, 'Chloe':18, 'Charlie':26, 'Megan':23}\n", "Adictionary" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_keys(['Chloe', 'Tom', 'Megan', 'Charlie', 'Jack'])" ] }, "execution_count": 65, "metadata": { }, "output_type": "execute_result" } ], "source": [ "Adictionary.keys()\n" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_values([18, 36, 23, 26, 34])" ] }, "execution_count": 66, "metadata": { }, "output_type": "execute_result" } ], "source": [ "Adictionary.values()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "__6.__ (1 point) The next cell generates 10,000 digits (numbers = 0,1,2,3,4,5,6,7,8,9). Count the number of times that a digit is between __a__ and __b+1__ (including __a__ and excluding __b+1__)." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([3, 8, 5, ..., 1, 1, 6])" ] }, "execution_count": 1, "metadata": { }, "output_type": "execute_result" } ], "source": [ "from numpy.random import randint\n", "\n", "ArrayOfDigits = randint(0,10,10000)\n", "ArrayOfDigits" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2041\n" ] } ], "source": [ "a,b,c,d=5,6,7,9\n", "from numpy.random import randint\n", "ArrayOfDigits=randint(0,10,10000)\n", "count=0\n", "for num in ArrayOfDigits:\n", " if num>=a and num2:\n", " maxPrime = n\n", " return int(maxPrime)\n", "print (maxPrimeFactor(394)) \n", " " ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "collapsed": false }, "outputs": [ ], "source": [ ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (Anaconda)", "language": "python", "name": "anaconda3" }, "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.5.5" }, "name": "1-GettingStartedwithPython.ipynb" }, "nbformat": 4, "nbformat_minor": 0 }