Hacking Math I

Spring 2020

drawing

Topic 2: Basic Data & Programming Structures

This topic:

  1. Basic Data Structions
  2. Functions

Readings:

  • "Coding the Matrix" Chapters 0 and 1.
  • Tons of Jupyter and Python resources on internet.

I. Basic Data Structures

Mathematical Data structures

  • Sets
  • Vectors
  • Matrices

Python Data structures ("collections")

  • Sets
  • Lists
  • Tuples
  • Dictionaries

Numerical precision - where numbers meet computers

  • Bytes/words, ints, floats, doubles... how big are they?
  • IEEE 745 standard numerical arithmetic
  • nan, inf, eps
  • "Hard zeros"

(Mathematical) Sets review

$$S=\{element_1,element_2,element_3\}$$
  • Elements
  • Subsets
  • Cardinality
  • Examples: Integers, Reals, Vector Spaces
  • Cartesian products of sets, Ex. $\mathbb R^n$

Fields (sets)

A set with "+" and "x" operations (that work properly).

  • Reals $\mathbb R$
  • Complex numbers $\mathbb C$
  • GF(2)

Python Sets {item1, item2, item3}

  • Order is not necessarily maintained
  • Each item occurs at most once
  • Mutable

Exercise: Create a set with a repeated value in and print it

In [11]:
S={1,2,2,3,4}
print(S)
{1, 2, 3, 4}

Exercise: Compute the cardinality of your set

In [9]:
print(len(S))
4

Python Sets ... handy functions

  • sum()
  • logical test for membership
  • add(), remove(), update()
  • copy() -- NOTE: Python "=" binds LHS to RHS by reference, it is not a copy.
In [1]:
S={1,2,2,3,4}
T = S
T.add(6)
print(T)
print(S)
{1, 2, 3, 4, 6}
{1, 2, 3, 4, 6}
In [13]:
S={1,2,2,3,4}
T = S.copy()
T.add(6)
print(T)
print(S)
{1, 2, 3, 4, 6}
{1, 2, 3, 4}

Everything is a class

In [5]:
dir(T)
Out[5]:
['__and__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__iand__',
 '__init__',
 '__init_subclass__',
 '__ior__',
 '__isub__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__or__',
 '__rand__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__ror__',
 '__rsub__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__xor__',
 'add',
 'clear',
 'copy',
 'difference',
 'difference_update',
 'discard',
 'intersection',
 'intersection_update',
 'isdisjoint',
 'issubset',
 'issuperset',
 'pop',
 'remove',
 'symmetric_difference',
 'symmetric_difference_update',
 'union',
 'update']

Q: Is a set a good data structure to make vectors and do linear algebra?

Python Lists [item1, item2, item3]

  • Sequence of values - order maintained & repeats ok
  • Mutable
  • Concatenate lists with "+"
  • Index with mylist[index] - note zero based

Convert your set to a list, print list, its length, it's first and last elements

Slices - mylist[start:end:step]

Matlabesque way to select sub-sequences from list

  • If first index is zero, can omit - mylist[:end:step]
  • If last index is length-1, can omit - mylist[::step]
  • If step is 1, can omit mylist[start:end]

Make slices for even and odd indexed members of your list.

Q: Is a list a good data structure to make vectors and do linear algebra?

Mathematical indexing and Colon Notation

  • $a_i$ as $i^{th}$ element of vector $a$
  • $a_{start:end}$ as "subvector" of vector $a$
  • See I2ALA Chapter 1

Exercise:

  • suppose you have a Python list $L$ storing vector $a$
  • how do you extract $a_5$?
  • how do you extract the subvector $a_{1:5}$?

Python Tuples (1,2,3)

  • Immutable version of list basically
In [13]:
(1,2,3)[0:2] # note can access directly
Out[13]:
(1, 2)
  • Handy for packing info
  • sometimes omit the parenthesis
In [15]:
a,b=1,2
print(a,b)
1 2

The constructors

  • convert other collections (and iterators) into collections
In [32]:
L = list(S)
S = set(L)
T = tuple(S)

Python Dictionaries {key1:value1,key2:value2}

  • key:value ~ word:definition
  • access like a generalized list
In [38]:
mydict = {0:100,1:200,3:300}
mydict[0]
Out[38]:
100
In [8]:
mydict = {'X':'hello','Y':'goodbye'}
mydict['X']
Out[8]:
'hello'

Dictionaries ... handy functions

In [9]:
print(mydict.keys())
print(mydict.values())
print(mydict.items())
dict_keys(['X', 'Y'])
dict_values(['hello', 'goodbye'])
dict_items([('X', 'hello'), ('Y', 'goodbye')])

Q: How would you use a dictionary to make a vector?

II. Functions and control structures

Mathematical Function $f(x) = y$

  • Rule that assigns input to output
  • Mapping between sets
  • Composition $g(f(x)) = z$
  • Probablity as a function $P(x) = p$

Inverse function $x = f^{-1}(y)$

  • Forward versus Backward Problem
  • One-to-one
  • Onto

Procedure

  • Description of a computation
  • Also called "function" (but not CTM)
  • Versus "computational problem"

Python function

In [23]:
def f(x):       # <--- def keyword and colon after name and arguments
    print('hi') # <--- contents must have same indent
    return x**2 # <--- return output

y = f(4)
print("y =",y)
hi
y = 16

Exercise: make a function to count number of unique values in a list

Conditional Statements

In [47]:
if not (2+2 == 4):     
    print('tree')
else:
    print('hi')
hi

Conditional mathematical statements

$$y = \begin{cases} -1, x \le 0 \\ +1, x > 0 \end{cases}$$

Exercise: implement this with a python function

Python Comprehensions "x for x in mydatastructure"

  • Uses iterators for generating sets/lists/tuples
  • Similar to mathematical set notation $\{ x : x \in S\}$
  • popular in "Coding the Matrix"
In [31]:
L=[2*i for i in {1,2,3}]
print(L)
[2, 4, 6]

Exercise: implement $\{x^2 : x \in L\}$ for your list $L$

(i.e., iterate over list and produce list squared)

In [56]:
L=[1,1,2,3,4,4,5]

Exercise: Iterate over dictionary and swap keys with values

Loops

In [35]:
for x in {1,2,3}:    
    print(x)
    print(x*x)
1
1
2
4
3
9

Whitespace

  • used for grouping code
  • same indent = same group
  • nested code = increased indent
  • must be used properly
In [34]:
for x in {1,2,3}: 
    print(x)
    for y in {1,2,3}: # a nested loop
        print('...',x,y)
1
... 1 1
... 1 2
... 1 3
2
... 2 1
... 2 2
... 2 3
3
... 3 1
... 3 2
... 3 3
In [45]:
x=0
while x<5:
    print(x)
    x=x+1
0
1
2
3
4

Math loops... summations

A function, though we often just write the function contents "inline"

$$\sum_{i=1}^N x_i = x_1+x_2+...+x_N = "sum(x)"$$

Exercise: implement the sum over your list with a loop

(you can compare to built-in functions "sum()", but use a loop for this exercise)

Range Iterator

Used for making a list of incremental numbers to loop over

In [38]:
range(10,0,-1)
Out[38]:
range(10, 0, -1)
In [17]:
list(range(10,0,-1)) # construct list using iterator
Out[17]:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
In [18]:
for x in range(0,10): # loop over iterator
    print(x)
0
1
2
3
4
5
6
7
8
9

Classes in Python

Clunky but handy to encapsulate related code. Feel free to avoid writing any.

Note odd way that constructor is defined

Also need to pass "self" argument to every function

In [28]:
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
Out[28]:
(3.0, -4.5)
In [ ]: