<jupyter_start><jupyter_text>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 acollection 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. ![](array-image.jpg)In the figure, the variable name is `MyList`, the subscripts are replaced by an indexwhich 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 ManipulationFor 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]**<jupyter_code>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)<jupyter_output>Sliced_list:  [87, 10, 97, 88, 75, 99, 11, 19]
Sum:  486
Length:  8<jupyter_text>Exercise-2: List ManipulationFrom 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]**<jupyter_code>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)<jupyter_output>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]<jupyter_text>Special List - TupleA 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 - DictionaryA 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 adatabase 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:<jupyter_code># 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!<jupyter_output>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<jupyter_text>Exercise-3: 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']}]}]}**<jupyter_code>mydict = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}

mydict['k1'][3]['tricky'][3]['target'][3]<jupyter_output><empty_output><jupyter_text>2) Conditional Execution Conditional statements are logical expressions that evaluate as TRUE or FALSE and usingthese results to perform further operations based on these conditions.All flow control in a program depends on evaluating conditions. The program will proceeddiferently 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. ComparisonThe most common conditional operation is comparison. If we wish to compare whether twovariables 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, ` `larger than, `=` 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 `TRUE`because the first condition is true.The `not` operator returns `TRUE` if the condition after the `not` keyword is false. Think of itas a way to do a logic reversal.<jupyter_code># 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)
# 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)<jupyter_output>5 == 5 and 5 < 6 ?  True
4 > 3 or 17 > 20  True
not 5 == 5 False<jupyter_text>Block `if` statementThe `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 stringso 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 executethe 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"<jupyter_code># 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")<jupyter_output>Enter the number 1 or 2 f<jupyter_text>Inline `if` statementAn inline `if` statement is a simpler form of an `if` statement and is more convenient if youonly 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    num1An alternative way is to enclose the condition in brackets for some clarity like    myInt = 3    num1 = 12 if (myInt == 0) else 13    num1In 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 ExecutionA 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.<jupyter_code>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")<jupyter_output>Enter total classes held 50
Enter classes attended 32<jupyter_text>Exercise-6: RoboCop ModificationYou 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.<jupyter_code># 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')<jupyter_output>How Fast ? (numeric) 80
Is it your birthday?  (Yes or No) Yes
{'fraction_non_alphanumeric': 0.09529303184125519, 'fraction_numerical': 0.03430241501307491, 'mean_word_length': 4.2304907481898635, 'pattern_counts': {'":': 7, '<': 31, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '55059', 'license': 'CC0-1.0', 'n_tokens_mistral': 4158, 'n_tokens_neox': 3753, 'n_words': 1911, 'path': '1-Lessons/Lesson03/dev_src/Lab3-Obsolete/.ipynb_checkpoints/Lab3-checkpoint.ipynb', 'repo_name': 'dustykat/engr-1330-psuedo-course', 'size': '13002'}