Data Structures
["apple","banana"] # list, ordered, dynamic array implementation
("apple", "banana") # tuple, immutable list
{"apple", "banana"} # set, not ordered, no duplicates allowed
range(6) # range, integers in range(from, to)
{"name":"apple", "price":10} # dict
map function:
map(function, iterable) applies the function on every element of the iterable
lists
- lists cannot be used as keys in dictionaries, have to be converted to tuple
- list slicing
list[start:end:step]with start inclusive and end exclusive; slicing a list
returns a copy of it
- methods on lists
insert()
append() # insert at last index
extend() # concat two collections together
remove(item)
pop(index) # same as remove
sort() # sorting is in place, this method doesn't return anything
copy() # deep copy
index() # return index of an element
count() # return num of elements with specific value
# tuple are imutable, some of these methods are not applicable, but mostly the same
dictionaries
sets
- python version of a hashset, or, a hashmap with only the keys
- methods on sets
add()
remove()
"mystr" in myset # check membership, O(1)
set1 | set2 # union
set1 & set2 # intersection
set1 - set2 # diff between the two sets
# one thing to note is that | and & has lower priority than -, so use parenthese when you do set operations
stack, queue and priority queue
stacks: just use a list as a stack with
append() and
pop()
queue:
from collections import dequeue it's a bi-directional queue
priority queue:
import heapq or
from queue import PriorityQueue
NumPy
Some general rules in numpy:
1. in indexing, a comma
, means indexing another dimension
2. in slicing, a colon
: means one of
start:end:step
3. axis=0 means do the operation row-wise and axis=1 means do the operation column-wise
- properties of a numpy array
np.dtype(object) # the data type of the data contained in this array, should be homogeneous
np.shape(nparray) # a tuple (axis1, axis2...)
np.size(nparray) # number of elements, which is the product of the shape
np.ndim(nparray) # number of axes
- creating an numpy array
np.zeros(10)
np.ones(10)
np.empty(10)
np.array([1,2,3])
np.arange(start,end,step)
np.linspace(start,end,num=10) # slice the range between start and end into 10 slices
rng = np.random.default_rng()
rng.integers(5, size=(2,4)) # generate random integers in range [0,5) into a nparray of shape (2,4)
- operations on numpy array shapes
np.concatenate((nparray1, nparray2), axis=?) # axis=0 stack these two row-wise, as if adding more rows; axis=1 add these two column-wise, as if appending more columns
np.hstack() # horizontal stack, same as axis=0
np.vstack() # vertical stack, same as axis=1
nparray1.reshape(some shape) # size must match
nparray.transpose() # same as nparray.T
nparray.flatten() # flatten an nparray into 1d! if you want other dimension use reshape
- arithmatics on numpy array
nparray1 + nparray2 # this is NOT concat, this is really adding the values for each entry of the two arrays; similarly you can do - * /
# their shapes have to match, with one exception: adding a single row or column. that single row/column will be expanded into a nparray with the same shape
min(), max(), sum() # can specify the axis for the operation
- rubrics
sort(nparray)
np.unique(nparray) # get unique values in an nparray
nparray2 = nparray1.copy() # deep copy
nparray[nparray>5] # returns all elements in the array with value greater than 5, regardless of the shape of the array
np.flip(nparray, axis=?) # flip an array means reversing the elements in the array
OOP
Everything in python classes are public.
More on Python magic methods,
see here
# skeleton code for a python class
class MyClass:
myProperty = 1
def __init__(self, propValue): # this is one of the magic methods of Python classes
self.myProperty = propValue
def myMethod():
# do something
def myMethod2(self): # self refers to this object; doesn't have to be self, but must be the first parameter
# do something with this object
# inheritance
class MyChildClass(MyClass):
def inheritedMethod1():
super().myMethod()
# do something else here
# how you would use a python class
myObject = MyClass(100)
print(myObject.myProperty)
myObject.myMethod2()
Matplotlib
Pyplot
You can't really plot a function directly.
To plot a function, you have to use numpy to create a list of points and then plot these points.
x = np.arange(0,1)
y = np.log(math.comb(100, 40)) # put your function here
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()