1 07-Containers


Previous: 06-Loops.html

Q: **Why did the programmer get fired from his job?**
A: **Because he didn't get arrays.**

1.1 Screencasts

1.2 Reading

1.3 Announcements for the day

1.4 Containers

A container groups items together under one name.

1.5 Arrays

https://en.wikipedia.org/wiki/Array_data_type
https://en.wikipedia.org/wiki/Array_data_structure
An array data structure, or simply an array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

These * [ ] are brackets
These { } are braces
These ( ) are parentheses

These * [ ] are used to index into arrays in most languages!

Each array is named, and that name is used with the above brackets.

1.5.1 Indexing

Say it with me:
07-Containers/count0.jpg
…repeat after me.
https://en.wikipedia.org/wiki/Zero-based_numbering
Some languages start indexing at 1 (MATLAB, Lua), but the vast majority start indexing at 0.

Starting at 0 is not just an arbitrary choice, and there are actual benefits:
* http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
* https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm

my_array[3] is highlighted in red:
07-Containers/array.jpg
It’s the fourth element!

++++++++++++++++
Cahoot-07.1
https://mst.instructure.com/courses/58101/quizzes/55609

07-Containers/arrayex.jpg
What is Array[4]?

1.6 Arrays with extra stuff, in python: Lists

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# RTFM
help(list)
"""
https://stackoverflow.com/questions/24735311/what-does-the-slash-mean-in-help-output
A slash in the argument list of a function denotes that the parameters prior to it are positional-only.
Positional-only parameters are the ones without an externally-usable name.
Upon calling a function that accepts positional-only parameters,
arguments are mapped to parameters based solely on their position.
"""

Using these functions, lists can be modified in-place, and thus are called mutable.

1.6.1 Looping through Lists

For example to load a list and search for a value (searching for key):
07-Containers/containers_00_search.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
input: 2 3 4 5 6 7 -1
"""

from typing import List

key: int = 5
tempvalue: int = int(input())
numbers: List[int] = []
i: int = 0

while tempvalue != -1:
    numbers.append(tempvalue)
    tempvalue = int(input())
    i = i + 1

for i in range(len(numbers)):
    if numbers[i] == key:
        print("Your key of", key, "appears first at the following index: ", i)
        break
07-Containers/containers_00_search_cfg.svg

1.6.2 Common mistakes

https://en.wikipedia.org/wiki/Off-by-one_error
(The MOST common programming bug!!!)

07-Containers/containers_01_range.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Range is inclusive to exclusive.
"""

for index in range(0, 5):
    print(index)
    # Do other stuff here
07-Containers/containers_01_range_cfg.svg

1.6.2.1 Security vulnerabilities?

07-Containers/containers_02_off.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
An array variable holds many values rather than just one value.
The size can be read as lin(nameofarray)
useful in loops iterating through the array.
myarray: List[type] = []
myarray: List[type] = [item, item, ...]
user_array[expression] accesses elements
user_array[expression] can be any valid expression that produces an index
"""

from typing import List

user_nums: List[int] = list([0] * 5)

for i in range(len(user_nums) + 1):
    print(i)
    user_nums[i] = i * 2

x: int = user_nums[3]

for inum in user_nums:
    print(inum)
07-Containers/containers_02_off_cfg.svg

1.7 Example problems

++++++++++++++++
Cahoot-07.2
https://mst.instructure.com/courses/58101/quizzes/55610

07-Containers/containers_03_primes.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Enters and outputs the lowest positive primes
"""

from typing import List

prime_array: List[int] = []

prime_array.append(2)
prime_array.append(3)
prime_array.append(5)
prime_array.append(7)
prime_array.append(11)

print("Low primes are: ")

# range(start, stop, step)
for i in range(len(prime_array) - 1, -1, -1):
    print(prime_array[i])

07-Containers/containers_03_primes_cfg.svg
Another option to range(start, stop, step): 07-Containers/containers_03_primes_alt.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Enters and outputs the lowest positive primes
"""

from typing import List

prime_array: List[int] = []

prime_array.append(2)
prime_array.append(3)
prime_array.append(5)
prime_array.append(7)
prime_array.append(11)

print("Low primes are: ")

for prime in reversed(prime_array):
    print(prime)

Averaging some floats
07-Containers/containers_04_average.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Averaging some floats
"""

from typing import List

my_array: List[float] = []

my_array.append(2.1)
my_array.append(3.4)
my_array.append(5.3)

print("The average of these numbers is: ")
print((my_array[0] + my_array[1] + my_array[0 + 2]) / 3)
# Weird indexing just to show example

# or
print(sum(my_array) / len(my_array))

Our exponent program from last time, modified for lists (it’s not really ideally efficient, why?)
07-Containers/containers_05_exp.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Exponentiation
"""

from typing import List

base: int = 2
exponent: int = 16
total: int = 1
binary_array: List[int] = []

for counter in range(0, exponent):
    total = total * base
    binary_array.append(total)

for exp in binary_array:
    print(exp)
07-Containers/containers_05_exp_cfg.svg

Our prime program extended from last class (loops), now more efficient, and with lists:
07-Containers/containers_06_trialdiv.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
https://en.wikipedia.org/wiki/Trial_division
"""

from math import sqrt
from typing import List

# smallest prime is 2, how odd...
value: int = 2

max_value: int = int(input("Display primes up to what value?"))
primes: List[int] = []

while value <= max_value:
    is_prime: int = 1
    trial_factor: int = 2

    # squrt quit is more efficient:
    while trial_factor < sqrt(value):
        if value % trial_factor == 0:
            is_prime = 0
            # breaking is more efficient
            break
        trial_factor = trial_factor + 1

    if is_prime == 1:
        primes.append(value)
        print(value, " is prime")
    else:
        print(value, " is not prime")

    value = value + 1

print("\nThe primes are", primes)
07-Containers/containers_06_trialdiv_cfg.svg

User’s are often malicious or confused (or don’t read instructions… which many of you have learned the hard way!)
07-Containers/containers_07_outofrange.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
IndexError!
"""

from typing import List

user_nums: List[int] = list([0] * 5)
limit = int(input("How high do you want to count by 2s (1-5 only!)"))

for i in range(limit):
    user_nums[i] = i * 2

for item in user_nums:
    print(item)

How do we fix that?
07-Containers/containers_07_outofrange_cfg.svg
You fix the program!

Read errors!!!
07-Containers/indexerror.png
Python is trying to help you and extend a hand, so reach out and take it’s hand (read)!

1.7.1 Caesar extended

1.7.1.1 Key generation (correct)

07-Containers/containers_08_caesar_keygen.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import random

print("Your randomly chosen Caesar cipher key is: ")
print(random.randint(1, 25))
print("\n Share securily with your communication partner, and don't tell anyone else\n")

1.7.1.2 Encryption and decryption (new bug, missing features)

from typing import List

key: int = int(input(“your Caesar key in numeric form (1-25):”))
mode: int = int(input(“ for encryption, and 0 for decryption:”))

caesar_encoding: str = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
message: str = input(“your message, in English:”)
translated: List[int] = []

for character in message:
if mode == 1:
# 26 is the symbol set size (# letters in alphabet)
encoded_char = caesar_encoding.find(character.upper())
translated.append((encoded_char + key) % 26)
else:
encoded_char = caesar_encoding.find(character.upper())
translated.append((encoded_char - key) % 26)

print(“encrypted text is:”)
# To print the string:
for encoded_char in translated:
print(caesar_encoding[encoded_char], end=““)

2 Another way to recover the string for later use, if needed:

plaintext: List[str] = []
for counter, encoded_char in enumerate(translated):
plaintext.append(caesar_encoding[encoded_char])

plaintext_string: str = ““.join(plaintext)
print(plaintext_string)
```

07-Containers/containers_09_caesar_for_cfg.svg
This program really wraps up a lot of what we have learned, so read it, trace it, play with it, and understand it!

2.1 Language focus

To be stepped through in the python3-spyder IDE and/or python3-pudb debugger:
07-Containers/containers_10_overview.py
07-Containers/containers_11b_lists.py

++++++++++++ Lecture 1 ends here ++++++++++++
++++++++++++ Lecture 2 starts here ++++++++++++

2.2 2D Lists

Matrix indexing in Math follows this convention, starting indexing from the bottom left, the origin, (0, 0), of the matrix (positive quadrant):

~~list[x][y]~~
~~list[horizontal][vertical]~~

07-Containers/math_axes.png
* This is NOT how we do it in computer science.

CS indexes n-D structures in the opposite indexing pattern, and starts indexing from the top left:

2D Lists:
list[down][over]
list[row][col]

Generally posed, nD Lists:
list[outermost][innermore][...][innermost]

07-Containers/two-dimensional-array.png
* You should ALWAYS assume and code your matrices the CS way, in this and all future CS classes!

2.2.1 Code

++++++++++++++++
Cahoot-07.3
https://mst.instructure.com/courses/58101/quizzes/55670

2.3 Language focus

To be stepped through in the python3-spyder IDE and/or python3-pudb debugger:
07-Containers/containers_10_overview.py
07-Containers/containers_12_tuples.py
07-Containers/containers_13_sets.py
07-Containers/containers_14_frozensets.py
07-Containers/containers_15_dictionaries.py
07-Containers/containers_16_conversions.py
07-Containers/containers_17_slicing_n_dicing.py (READ THIS!)
07-Containers/containers_18_identity_referencing.py
07-Containers/containers_19_membership.py
07-Containers/containers_20_sorting.py

++++++++++++++++
Cahoot-07.4
https://mst.instructure.com/courses/58101/quizzes/55671

Next: 08-Functions.html