In [1]:
# Preamble script block to identify host, user, and kernel
import sys
! hostname
! whoami
print(sys.executable)
print(sys.version)
print(sys.version_info)
atomickitty.aws
compthink
/opt/conda/envs/python/bin/python
3.8.3 (default, Jul  2 2020, 16:21:59) 
[GCC 7.3.0]
sys.version_info(major=3, minor=8, micro=3, releaselevel='final', serial=0)
In [2]:
%%html
<!--Script block to left align Markdown Tables-->
<style>
  table {margin-left: 0 !important;}
</style>

Laboratory 3. Data Structures and Conditional Execution

Data Structures

Lists (Array)

A list is a collection of data that are somehow related. It is a convenient way to refer to a collection of similar things by a single name, and using an index (like a subscript in math) to identify a particular item.

Consider the "math-like" variable $x$ below:

\begin{gather} x_0= 7 \\ x_1= 11 \\ x_2= 5 \\ x_3= 9 \\ x_4= 13 \\ \dots \\ x_N= 223 \\ \end{gather}

The variable name is $x$ and the subscripts correspond to different values. Thus the value of the variable named $x$ associated with subscript $3$ is the number $9$.

The figure below is a visual representation of a the concept that treats a variable as a collection of cells.

In the figure, the variable name is MyList, the subscripts are replaced by an index which identifies which cell is being referenced. The value is the cell content at the particular index.

So in the figure the value of MyList at Index = 3 is the number 9.'

In engineering and data science we use lists a lot - we often call then vectors, arrays, matrices and such, but they are ultimately just lists.

To declare a list you can write the list name and assign it values. The square brackets are used to identify that the variable is a list. Like:

MyList = [7,11,5,9,13,66,99,223]

One can also declare a null list and use the append() method to fill it as needed.

MyOtherList = [ ]

Python indices start at ZERO. Alot of other lnguages start at ONE. Its just the convention.

The first element in a list has an index of 0, the second an index of 1, and so on. We access the contents of a list by referring to its name and index. For example

MyList[3] has a value of the number 9.

Exercise-1: List Manipulation

For the list given below, index and pick all the elements from index positions 3 to 10. Then, calculate the sum and the length of the elements from index positions 3 to 7. Print the sliced list and the values of the sum and the sliced list.

[22, 45, 54, 87, 10, 97, 88, 75, 99, 11, 19, 39, 47, 81, 84]

In [3]:
mylist2 = [22, 45, 54, 87, 10, 97, 88, 75, 99, 11, 19, 39, 47, 81, 84]

myslicelist2 = mylist2[3:11]
print("Sliced_list: ", myslicelist2)

mysum = sum(myslicelist2)
print("Sum: ", mysum)

mylength = len(myslicelist2)
print("Length: ", mylength)
Sliced_list:  [87, 10, 97, 88, 75, 99, 11, 19]
Sum:  486
Length:  8

Exercise-2: List Manipulation

From the list given below, remove the element at the index position 4 and add it to the 2nd position and also, add it at the end of the list.
Print the original list and also the list after each step of altering the list elements.

['Bob', 44, 27, 'Joe', 91, 41, 54.555]

In [4]:
mylist1 = ['Bob', 44, 27, 'Joe', 91, 41, 54.555]
print("Original list: ",mylist1)

element = mylist1.pop(4)
print("List After removing element at index 4: ",mylist1)

mylist1.insert(2, element)
print("List after Adding element at index 2: ",mylist1)

mylist1.append(element)
print("List after Adding element at last: ",mylist1)
Original list:  ['Bob', 44, 27, 'Joe', 91, 41, 54.555]
List After removing element at index 4:  ['Bob', 44, 27, 'Joe', 41, 54.555]
List after Adding element at index 2:  ['Bob', 44, 91, 27, 'Joe', 41, 54.555]
List after Adding element at last:  ['Bob', 44, 91, 27, 'Joe', 41, 54.555, 91]

Special List - Tuple

A tuple is a special kind of list where the values cannot be changed after the list is created. It is useful for list-like things that are static - like days in a week, or months of a year. You declare a tuple like a list, except use round brackets instead of square brackets.

MyTupleName = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

Special List - Dictionary

A dictionary is a special kind of list where the items are related data PAIRS. It is a lot like a relational database (it probably is one in fact) where the first item in the pair is called the key, and must be unique in a dictionary, and the second item in the pair is the data. The second item could itself be a list, so a dictionary would be a meaningful way to build a database in Python.

To declare a dictionary using curly brackets

MyPetsNamesAndMass = { "Dusty":7.8 , "Aspen":6.3, "Merrimee":0.03}

To declare a dictionary using the dict() method

MyPetsNamesAndMassToo = dict(Dusty = 7.8 , Aspen = 6.3, Merrimee = 0.03)

Some examples follow:

In [5]:
# Tuples
MyTupleName = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
# Access a Tuple
print ("5th element of the tuple", MyTupleName[4])
# Dictionary
MyPetsNamesAndMass = { "Dusty":7.8 , "Aspen":6.3, "Merrimee":0.03}
# Access the Dictionary
print ("Aspen's mass = ", MyPetsNamesAndMass["Aspen"])
# Change a value in a dictionary
print ("Merrimee's mass" , MyPetsNamesAndMass["Merrimee"])
MyPetsNamesAndMass["Merrimee"] = 0.01
print ("Merrimee's mass" , MyPetsNamesAndMass["Merrimee"], "She lost weight !")
# Alternate dictionary
MyPetsNamesAndMassToo = dict(Dusty = 7.8 , Aspen = 6.3, Merrimee = 0.03)
print ("Merrimee's mass" , MyPetsNamesAndMassToo["Merrimee"])
# Attempt to change a Tuple
#MyTupleName[3]=("Fred") # Activate this line and see what happens!
5th element of the tuple May
Aspen's mass =  6.3
Merrimee's mass 0.03
Merrimee's mass 0.01 She lost weight !
Merrimee's mass 0.03

Exercise-3: Dictionary Manipulation

From the nested dictionary given below, index and pick the string 'hello'.

{'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}

In [6]:
mydict = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}
mydict['k1'][3]['tricky'][3]['target'][3]
Out[6]:
'hello'
In [ ]:
 

Conditional Execution

Conditional statements are logical expressions that evaluate as TRUE or FALSE and using these results to perform further operations based on these conditions. All flow control in a program depends on evaluating conditions. The program will proceed diferently based on the outcome of one or more conditions - really sophisticated AI programs are a collection of conditions and correlations. Amazon knowing what you kind of want is based on correlations of your past behavior compared to other peoples similar, butmore recent behavior, and then it uses conditional statements to decide what item to offer you in your recommendation items. It's spooky, but ultimately just a program running in the background trying to make your money theirs.

Comparison

The most common conditional operation is comparison. If we wish to compare whether two variables are the same we use the == (double equal sign).

For example x == y means the program will ask whether x and y have the same value. If they do, the result is TRUE if not then the result is FALSE.

Other comparison signs are != does NOT equal, < smaller than, >larger than, <=less than or equal, and >= greater than or equal.

There are also three logical operators when we want to build multiple compares (multiple conditioning); these are and, or, and not.

The and operator returns TRUE if (and only if) all conditions are TRUE. For instance 5 == 5 and 5 < 6 will return a TRUE because both conditions are true.

The or operator returns TRUE if at least one condition is true. If all conditions are FALSE, then it will return a FALSE. For instance 4 > 3 or 17 > 20 or 3 == 2 will return TRUEbecause the first condition is true. The not operator returns TRUE if the condition after the not keyword is false. Think of it as a way to do a logic reversal.

In [7]:
# Compare
x = 7
y = 10
print("x =: ",x,"y =: ",y)
print("x is equal to y : ",x==y)
print("x is not equal to y : ",x!=y)
print("x is greater than y : ",x>y)
print("x is less than y : ",x<y)
x =:  7 y =:  10
x is equal to y :  False
x is not equal to y :  True
x is greater than y :  False
x is less than y :  True
In [8]:
# Logical operators
print("5 == 5 and 5 < 6 ? ",5 == 5 and 5 < 6)
print("4 > 3 or 17 > 20 ",4 > 3 or 17 > 20)
print("not 5 == 5",not 5 == 5)
5 == 5 and 5 < 6 ?  True
4 > 3 or 17 > 20  True
not 5 == 5 False

Block if statement

The if statement is a common flow control statement. It allows the program to evaluate if a certain condition is satisfied and to perform a designed action based on the result of the evaluation. The structure of an if statement is

if condition1 is met:
    do A
elif condition 2 is met:
    do b
elif condition 3 is met:
    do c
else:
    do e

The elif means "else if". The : colon is an important part of the structure it tells where the action begins. Also there are no scope delimiters like (), or {} . Instead Python uses indentation to isolate blocks of code.

This convention is hugely important - many other coding environments use delimiters (called scoping delimiters), but Python does not. The indentation itself is the scoping delimiter.

The next code fragment illustrates illustrates how the if statements work. The program asks the user for input. The use of raw_input() will let the program read any input as a string so non-numeric results will not throw an error. The input is stored in the variable named userInput. Next the statement if userInput == "1": compares the value of userInput with the string "1". If the value in the variable is indeed \1", then the program will execute the block of code in the indentation after the colon. In this case it will execute

print "Hello World"
print "How do you do? "

Alternatively, if the value of userInput is the string '2', then the program will execute

print "Snakes on a plane "

For all other values the program will execute

print "You did not enter a valid number"
In [9]:
# Block if example
userInput = input('Enter the number 1 or 2')
# Use block if structure
if userInput == '1':
    print("Hello World")
    print("How do you do? ")
elif userInput == '2':
    print("Snakes on a plane ")
    print("You did not enter a valid number")
else:
    print("You did not enter 1 or 2")
Hello World
How do you do? 

Inline if statement

An inline if statement is a simpler form of an if statement and is more convenient if you only need to perform a simple conditional task. The syntax is:

do TaskA `if` condition is true `else` do TaskB

An example would be

myInt = 3
num1 = 12 if myInt == 0 else 13
num1

An alternative way is to enclose the condition in brackets for some clarity like

myInt = 3
num1 = 12 if (myInt == 0) else 13
num1

In either case the result is that num1 will have the value 13 (unless you set myInt to 0).

One can also use if to construct extremely inefficient loops.

Exercise-4: Use of Conditional Execution

A student will not be allowed to sit in exam if his/her attendence is less than 75%. Take the following inputs from the user:

1. Number of classes held.
2. Number of classes attended. 

Compute the percentage of classes attended

$$\%_{attended} = \frac{Classes_{attended}}{Classes_{total}}*100$$

Use the result to decide whether the student will be allowed to sit in the exam or not.

In [10]:
nc_held = 50
nc_attended = 32
nc_held = input('Enter total classes held')
nc_attended = input('Enter classes attended')
attendance = int(nc_attended)/int(nc_held)*100
print('Attendance:', attendance,' percent')

if attendance >= 75:
    print("Allowed to sit in exam")
else:
    print("Not allowed to sit in exam")
Attendance: 37.5  percent
Not allowed to sit in exam

Exercise-6: RoboCop Modification

You are driving too fast, and a robotic police officer stops you. The robot is programmed with conditional statements to return one of 3 possible results: "No ticket","One hundred dollar fine", or "Five hundred dollar fine". according to the following rules

  • If your speed is 60 or less, the result is "No Ticket".
  • If speed is between 61 and 80 inclusive, the result is a fine of \$100.
  • If speed is 81 or more, the result is \$500.
  • If it is your birthday, your speed can be higher by a value of 5 in all cases.

You discover you are able to hack into the robot and can modify the fine script.

Modify it so that:

  • If speed is between 75 and 85 inclusive, the result is a fine of \$100.
  • If speed is 86 or more, the result is \$500.

Leave the rest unchanged.

In [11]:
# Input Speed
speed = int(input('How Fast ? (numeric)'))
# Input Birthday
yes = 0
# while loop 
while yes == 0:
    userInput = input('Is it your birthday?  (Yes or No)')
    try:
        if userInput == 'Yes':
            is_birthday = True
        elif userInput == 'No':
            is_birthday = False
        yes = 1
    except:
        print ("You did not enter Yes or No, try again \n")
# Exit the while loop when finally have a valid answer

if is_birthday:
    alterspeed = speed-5
else:
    alterspeed = speed
    
if alterspeed > 80:    
    print('Fine = $500')
elif alterspeed > 60:   
    print('Fine = $100')
else:
    print('No Ticket')
Fine = $100
In [ ]: