comparison operations types integer float string bool(1/0 ...use this to transpose a matrix...

2
Indexing and Slicing Index str/tup/list[i] Slice str/tup/list[start:stop:step] returns i-th index of str/tup/list Start Index to start Stop Index to stop (non-inclusive) Step Number of Indices to skip - 1 If negative, slices in reverse If i ≥ len(str/tup/list) Index Error If [start or stop ≥ len(str/tup/list)] or [stop < start and step > 0] No error, slice returned even if empty Indexation Table Forward Index 0 1 2 3 4 5 6 7 8 9 str/tup a b c d e f g h i j Reverse Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Negative Slicing a = ‘abcde’ a[-5:-2] >> ‘abc’ a[-2:-5] #integers are sliced forwards, so start < stop, not start > stop >> ‘’ a[-2:-5:-1] #reads indices backwards and hence can be sliced backwards >> ‘dcb’ Arithmetic Operations Types Integer Float String Bool(1/0) Tuple List Dict Integer ** * / // + - % ** * / // + - % * ** * / // + - % * * NA Float ** * / // + - % ** * / // + - % * ** * / // + - % * * NA String * * + * NA NA NA Bool(1/0) ** * / // + - % ** * / // + - % * ** * / // + - % * * NA Tuple * * NA * + NA NA List * * NA * NA + NA Dict NA NA NA NA NA NA NA Integers, Floats, Bool Compared numerically Tuple, Strings, Lists Compare the first non-equal values Else, compare by size Characters chr(97) = ‘a’ ord(‘a’) = 97 Compared lexicographically Char Ord ‘0’ – ’9’ 48-57 ‘A’ – ’Z’ 65-90 ‘a’ – ‘z’ 97-122 is/is not compares identity id(a) == id(b) ==/!= compares equivalence Operators Types Elements Calculation ** * / // + - % Comparison > >= < <= == != is Datatypes Types Examples Integers 1 2 3 Floats 1.0 2.1 3.001 Strings ‘ ‘ / “ “ ‘Cs1010s!’ ‘’ / “” Booleans True (1) False (0) Tuples (1,2,3) (1, True, ‘a’) () * When compared, Bool become 1/0 Truth Table AND TRUE FALSE OR TRUE FALSE NOT TRUE TRUE FALSE TRUE TRUE TRUE Negates bool/is/in FALSE FALSE FALSE FALSE TRUE FALSE Type Conversions Integer Float String Bool Tuple List Dictionary int() No change Floor of float Only for int strings 1 if True Not possible Not possible Not possible Turns strings to integers 0 if False float() float(5) = 5.0 No change For float and int strings 1.0 is True Not possible Not possible Not possible Turns strings to floats 0.0 if False str() str(5) = ‘5’ str(5.0) = ‘5.0’ No change ‘True’ if True str((1, 2)) = ‘(1, 2)’ str([1, 2]) = ‘[1, 2]str({1:2}) = ‘{1:2}’ ‘False’ if False bool() True True True if not empty No change True if not empty True if not empty True if not empty False if empty False if empty False if empty False if empty tuple() Not possible Not possible tuple(‘A1’) = (‘A’, ’1’) Not possible No change tuple([1,2]) = (1,2) list({1:2,3:4}) = [1,3] list() Not possible Not possible list(‘A1’) = [‘A’, ’1’] Not possible list((1, 2)) = [1, 2] No change tuple({1:2,3:4}) = (1,3) dict() Not possible Not possible Not possible Not possible dict(((1,2),)) = {1:2} dict([[1,2]]) = {1:2} No change Comparison Operations Types Integer Float String Bool(1/0) Tuple List Dict Integer > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == != Float > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == != String == != == != > >= < <= == != == != == != == != == != Bool(1/0) > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == != Tuple == != == != == != == != > >= < <= == != == != == != List == != == != == != == != == != > >= < <= == == != Dict == != == != == != == != == != == != == != A tuple or a list *False returns an empty tuple or list Useful List Functions Command Result Add to List l.append(ele) Adds an element to the back of the list as a new entry l.extend(ele) Opens apart an iterable and adds to the back of the list. Same as x = x + [list] or x += [list]. In a function, x = x + [list] creates a new list. l.insert(index, ele) Inserts element into given index of list Delete from List del l[index] Removes entry at given index in list l.remove(entry) Removes first occurrence of entry given l.pop(index) Removes entry at given index in list Make a Copy l.copy() Creates a shallow copy of list l[:] Creates a shallow copy of list import copy copy.deepcopy(l) Creates a deep copy of list Finding and Modifying an Entry l.index(entry) Returns index of first occurrence of given entry in list l[index] = new_val Changes the value at [index] to new_val Conversions list(range(val)) Returns a list of numbers in a given range tuple(l) Converts list to tuple s.join(l) Joins all strings in a list, separated by s Use s = ‘’ to convert list to string {x:y for x,y in l} Returns a dictionary of pairs now as key-value pairs {x:y for y,x in l} Returns a dictionary of pairs now as key-value pairs, but swapped Sorting a List l.sort() Sorts a list low to high. If entries are lists/tuples, sorts by index 0 l.sort(key, reverse) Or sorted(l, key, rev) Second returns the sorted list If entries are lists/tuples, and key is given, sorts based on key - key = lambda x: x[i] to sort based on i-th index - key = lambda x: -x[i] to sort based on i-th index, in reverse - key = lambda x: (x[i], x[j]) to sort based on i-th index, and then j-th index if i-th indices are the same If reverse = True, whole sort is reversed Flattening a List flat = [i for sublist in l for i in sublist] Flattens a list, Refer behind for deep flatten List Comprehension l = [f(i) for I in l] Applies f() to all entries in l Use list comprehension to filter and iterate through lists Useful Tuple Functions Command Result Add to Tuple t + ele Adds two tuples together if element is a tuple t + (ele,) Adds tuple with element if element is not a tuple Delete From Tuple Use slicing Returns new tuple Make a Copy t[:] Creates a shallow copy of tuple import copy copy.deepcopy(t) Creates a deep copy of tuple Conversions tuple(range(val)) Returns a tuple of numbers in a given range list(t) Converts tuple to list s.join(t) Joins all strings in a tuple, separated by s Use s = ‘’ to convert tuple to string {x:y for x,y in t} Returns a dictionary of pairs now as key-value pairs {x:y for y,x in t} Returns a dictionary of pairs now as key-value pairs, but swapped Useful Dictionary Functions: Command Result Adding/Deleting Keys **KEY MUST BE IMMUTABLE** d[new_key] = new_value Adds new_key and new_value to dictionary del d[key] Deletes key from dictionary d.pop(key, None) Deletes and returns key from dictionary, None will not raise error Getting Keys/Values using Values/Keys d[‘key’] Return value associated with the key ‘key’ [key for (key,val) in d.items() if val == ‘val’] Returns list of keys associated with the value ‘val’ Getting Tuples/Lists of Keys/Values tuple(d) or tuple(d.keys()) Returns tuple of keys list(d) or list(d.keys()) Returns list of keys tuple(d.values()) Returns tuple of values list(d.values()) Returns list of values Getting Tuples/List of Key-Value pairs list([k,v] for k,v in d.items()) Returns list of lists of key-value pairs tuple([k,v] for k,v in d.items()) Returns tuple of list of key-value pairs list(d.items()) Returns list of tuples of key-value pairs tuple(d.items()) Returns tuple of tuples of key-value pairs Getting maximum (replace with min for minimum) Keys/Values within a Dictionary max(d) or max(d.keys() Returns largest key max(d.values()) Returns largest value max(d, key = lambda x: d[x]) or max(d.keys(), key = lambda x: d[x]) Returns key whose value is the largest *Retuns first key if there are two largest values max(d.values(), key = lambda x: [key for (key,val) in d.items() if val == x]) Returns value whose key is the largest Filtering Dictionary Keys/Values d = {key:value for key,value in d.items() if f(key)} Returns dictionary of items where f(key) is true *Filter by key d = {key:value for key,value in d.items() if f(value)} Returns dictionary of items where f(value) is true *Filter by value “Mapping” a Dictionary d = {f(key):value for key, value in d.items()} Returns dictionary with f() applied to all keys d = {key:f(value) for key, value in d.items()} Returns dictionary with f() applied to all values d = {f(key):f(value) for key, value in d.items()} Returns dictionary with f() applied to all keys and values Make a Copy d.copy() Creates a shallow copy of dictionary import copy copy.deepcopy(d) Creates a deep copy of dictionary Modifying Table Values and Keys d[key] = new_value Replaces value associated with key with new_value d[new_key] = d.pop(old_key) Replaces old_key with new_key, value unchanged Converting Tuples/Lists to Dictionary, where each entry is a tuple/list pair {x:y for x,y in t/l} dict(t/l) Returns dictionary of key-value pairs originally tuple/list pairs {x:y for y,x in t/l} Returns dictionary of key-value pairs originally tuple/list pairs But order of pair is reversed Random Useful Python Stuff Command Result *arg in a function def fxn(msg, *args): print(msg, sum(args)) Accepts an arbitrary number of inputs from that argument onwards and treats all following arguments (inclusive of that argument) as one tuple inside the function fxn(‘hi’, 1, 2, 3) >> (‘hi, 6) – Over her, args is treated as a tuple map(function, l/t) Maps function to all entries in list or tuple. list()or tuple() to return as list or tuple filter(function, l/t) Filters & keeps entries that are True in func. list()or tuple() to return as list or tuple all(l/t) Use with map() to compare Returns True if all entries of a list or tuple are true all(map(function, seq)) Returns True if all entries in seq are True in function any(l/t) Use with map() to compare Returns True if any entry of a list or tuple is true any(map(function, seq)) Returns True if any entry in seq is True in function max(l/t), min(l/t) Returns highest, lowest value in a list or tuple (See left for dictionary) zip(*arg) >> list(zip([1,2,3,4],[1,2,3])) >> [(1,1),(2,2),(3,3)] Combines elements in corresponding indices of a mixture of lists, tuples, or ranges arguments into one tuple group per index. Stops at length of shortest argument. Use this to transpose a matrix [list(row) for row in zip(*mat)] [sum(i) for i in list(zip(*l))] Sums up l index-wise and returns sequence of sums Use list comprehension to change each entry to list since default is tuple for x,y,… in zip(*arg) Loops through a mixture of lists, tuples, or ranges and stops at the length of the shortest argument set(t/l) Removes repeats. Use with list()or tuple() to return as list or tuple x.count(i) Returns number of occurrences of i in x Useful String Functions *Space is included as a character in a string Command Result s.digit() Returns True if s is an integer s.isalpha() Returns True if s is a letter/word. Spaces return False s.replace(old, new, *number) Replaces all occurrences of old with new, unless a specified number is given s = s.join(iterable) Joins all strings in iterable, separated by s. Use s = ‘’ to convert iterable to string s.lower()/s.upper() Changes all characters in s to lowercase/uppercase s = ''.join(sorted(list(s))) Sorts a string lst = s.split() Splits a string at space into a list tuple(s) Returns tuple of individual characters in s list(s) Returns list of individual characters in s Useful Number Functions Command Result round(float, *decimals) Rounds a float to the given number of decimal place, if not, nearest integer abs(num) Returns absolute value of a number [int(dig) for dig in str(num)] Splits a number into individual digits as entries in a list from math import ceil ceil(float) Returns ceiling of float

Upload: others

Post on 03-Jan-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Comparison Operations Types Integer Float String Bool(1/0 ...Use this to transpose a matrix →[list(row) for row in zip(*mat)] [sum( i) for in list(zip(*l))] →Sums up l index-wise

Indexing and Slicing

Indexstr/tup/list[i]

Slicestr/tup/list[start:stop:step]

returns i-th index

of str/tup/list

Start Index to start

Stop Index to stop

(non-inclusive)

Step Number of Indices to skip - 1If negative, slices in reverse

If i ≥ len(str/tup/list) Index Error

If [start or stop ≥ len(str/tup/list)]or [stop < start and step > 0]

No error, slice returned even if empty

Indexation TableForward Index 0 1 2 3 4 5 6 7 8 9

str/tup a b c d e f g h i j

Reverse Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Negative Slicing

a = ‘abcde’a[-5:-2]>> ‘abc’a[-2:-5] #integers are sliced forwards, so start < stop, not start > stop>> ‘’a[-2:-5:-1] #reads indices backwards and hence can be sliced backwards>> ‘dcb’

Arithmetic Operations

Types Integer Float String Bool(1/0) Tuple List Dict

Integer ** * / // + - % ** * / // + - % * ** * / // + - % * * NA

Float ** * / // + - % ** * / // + - % * ** * / // + - % * * NA

String * * + * NA NA NA

Bool(1/0) ** * / // + - % ** * / // + - % * ** * / // + - % * * NA

Tuple * * NA * + NA NA

List * * NA * NA + NA

Dict NA NA NA NA NA NA NA

Integers, Floats, Bool Compared numerically

Tuple, Strings, ListsCompare the first non-equal values

Else, compare by size

Characters

chr(97) = ‘a’ord(‘a’) = 97

Compared lexicographically

Char Ord

‘0’ – ’9’ 48-57

‘A’ – ’Z’ 65-90

‘a’ – ‘z’ 97-122

is/is not compares identity – id(a) == id(b)==/!= compares equivalence

Operators

Types Elements

Calculation ** * / // + - %

Comparison > >= < <= == != is

Datatypes

Types Examples

Integers 1 2 3

Floats 1.0 2.1 3.001

Strings ‘ ‘ / “ “ ‘Cs1010s!’ ‘’ / “”

Booleans True (1) False (0)

Tuples (1,2,3) (1, True, ‘a’) ()

* When compared, Bool become 1/0

Truth Table

AND TRUE FALSE OR TRUE FALSE NOT

TRUE TRUE FALSE TRUE TRUE TRUE Negatesbool/is/inFALSE FALSE FALSE FALSE TRUE FALSE

Type Conversions

Integer Float String Bool Tuple List Dictionary

int() No change Floor of floatOnly for int strings 1 if True

Not possible Not possible Not possibleTurns strings to integers 0 if False

float() float(5) = 5.0 No changeFor float and int strings 1.0 is True

Not possible Not possible Not possibleTurns strings to floats 0.0 if False

str() str(5) = ‘5’ str(5.0) = ‘5.0’ No change‘True’ if True

str((1, 2)) = ‘(1, 2)’ str([1, 2]) = ‘[1, 2]’ str({1:2}) = ‘{1:2}’‘False’ if False

bool() True TrueTrue if not empty

No changeTrue if not empty True if not empty True if not empty

False if empty False if empty False if empty False if empty

tuple() Not possible Not possible tuple(‘A1’) = (‘A’, ’1’) Not possible No change tuple([1,2]) = (1,2) list({1:2,3:4}) = [1,3]

list() Not possible Not possible list(‘A1’) = [‘A’, ’1’] Not possible list((1, 2)) = [1, 2] No change tuple({1:2,3:4}) = (1,3)

dict() Not possible Not possible Not possible Not possible dict(((1,2),)) = {1:2} dict([[1,2]]) = {1:2} No change

Comparison Operations

Types Integer Float String Bool(1/0) Tuple List Dict

Integer > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == !=

Float > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == !=

String == != == != > >= < <= == != == != == != == != == !=

Bool(1/0) > >= < <= == != > >= < <= == != == != > >= < <= == != == != == != == !=

Tuple == != == != == != == != > >= < <= == != == != == !=

List == != == != == != == != == != > >= < <= == == !=

Dict == != == != == != == != == != == != == !=

A tuple or a list *False returns

an empty tuple or

list

Useful List FunctionsCommand Result

Add to List

l.append(ele) Adds an element to the back of the list as a new entry

l.extend(ele)Opens apart an iterable and adds to the back of the list. Same as x = x +

[list] or x += [list]. In a function, x = x + [list] creates a new list.

l.insert(index, ele) Inserts element into given index of list

Delete from List

del l[index] Removes entry at given index in listl.remove(entry) Removes first occurrence of entry given

l.pop(index) Removes entry at given index in list

Make a Copyl.copy() Creates a shallow copy of list

l[:] Creates a shallow copy of list

import copy

copy.deepcopy(l)Creates a deep copy of list

Finding and Modifying an Entry

l.index(entry) Returns index of first occurrence of given entry in list

l[index] = new_val Changes the value at [index] to new_valConversions

list(range(val)) Returns a list of numbers in a given range

tuple(l) Converts list to tuple

s.join(l)Joins all strings in a list, separated by s

Use s = ‘’ to convert list to string

{x:y for x,y in l} Returns a dictionary of pairs now as key-value pairs

{x:y for y,x in l} Returns a dictionary of pairs now as key-value pairs, but swapped

Sorting a Listl.sort() Sorts a list low to high. If entries are lists/tuples, sorts by index 0

l.sort(key, reverse)

Or

sorted(l, key, rev)

Second returns

the sorted list

If entries are lists/tuples, and key is given, sorts based on key

- key = lambda x: x[i] to sort based on i-th index

- key = lambda x: -x[i] to sort based on i-th index, in reverse

- key = lambda x: (x[i], x[j]) to sort based on i-th index, and

then j-th index if i-th indices are the same

If reverse = True, whole sort is reversed

Flattening a List

flat = [i for sublist in l for i in sublist] Flattens a list, Refer behind for deep flattenList Comprehension

l = [f(i) for I in l] Applies f() to all entries in l

Use list comprehension to filter and iterate through lists

Useful Tuple FunctionsCommand Result

Add to Tuplet + ele Adds two tuples together if element is a tuplet + (ele,) Adds tuple with element if element is not a tuple

Delete From TupleUse slicing Returns new tuple

Make a Copyt[:] Creates a shallow copy of tupleimport copy

copy.deepcopy(t)Creates a deep copy of tuple

Conversionstuple(range(val)) Returns a tuple of numbers in a given rangelist(t) Converts tuple to list

s.join(t)Joins all strings in a tuple, separated by s

Use s = ‘’ to convert tuple to string{x:y for x,y in t} Returns a dictionary of pairs now as key-value pairs{x:y for y,x in t} Returns a dictionary of pairs now as key-value pairs, but swapped

Useful Dictionary Functions:Command Result

Adding/Deleting Keys **KEY MUST BE IMMUTABLE**d[new_key] = new_value Adds new_key and new_value to dictionarydel d[key] Deletes key from dictionary

d.pop(key, None)Deletes and returns key from dictionary, None

will not raise errorGetting Keys/Values using Values/Keys

d[‘key’] Return value associated with the key ‘key’

[key for (key,val) in d.items() if val == ‘val’]Returns list of keys associated with the value

‘val’Getting Tuples/Lists of Keys/Values

tuple(d) or tuple(d.keys()) Returns tuple of keyslist(d) or list(d.keys()) Returns list of keystuple(d.values()) Returns tuple of valueslist(d.values()) Returns list of values

Getting Tuples/List of Key-Value pairslist([k,v] for k,v in d.items()) Returns list of lists of key-value pairstuple([k,v] for k,v in d.items()) Returns tuple of list of key-value pairslist(d.items()) Returns list of tuples of key-value pairstuple(d.items()) Returns tuple of tuples of key-value pairs

Getting maximum (replace with min for minimum) Keys/Values within a Dictionarymax(d) or max(d.keys() Returns largest keymax(d.values()) Returns largest valuemax(d, key = lambda x: d[x]) or

max(d.keys(), key = lambda x: d[x])

Returns key whose value is the largest

*Retuns first key if there are two largest valuesmax(d.values(), key = lambda x: [key for

(key,val) in d.items() if val == x])Returns value whose key is the largest

Filtering Dictionary Keys/Valuesd = {key:value for key,value in d.items() if

f(key)}

Returns dictionary of items where f(key) is true

*Filter by key

d = {key:value for key,value in d.items() if

f(value)}

Returns dictionary of items where f(value) is

true

*Filter by value“Mapping” a Dictionary

d = {f(key):value for key, value in d.items()} Returns dictionary with f() applied to all keysd = {key:f(value) for key, value in d.items()} Returns dictionary with f() applied to all values

d = {f(key):f(value) for key, value in d.items()}Returns dictionary with f() applied to all keys

and valuesMake a Copy

d.copy() Creates a shallow copy of dictionaryimport copy

copy.deepcopy(d)Creates a deep copy of dictionary

Modifying Table Values and Keys

d[key] = new_valueReplaces value associated with key with

new_value

d[new_key] = d.pop(old_key)Replaces old_key with new_key, value

unchangedConverting Tuples/Lists to Dictionary, where each entry is a tuple/list pair

{x:y for x,y in t/l}

dict(t/l)

Returns dictionary of key-value pairs originally

tuple/list pairs

{x:y for y,x in t/l}

Returns dictionary of key-value pairs originally

tuple/list pairs

But order of pair is reversed

Random Useful Python StuffCommand Result

*arg in a function

def fxn(msg, *args):

print(msg, sum(args))

Accepts an arbitrary number of inputs from that argument onwards and treats all

following arguments (inclusive of that argument) as one tuple inside the function

fxn(‘hi’, 1, 2, 3) >> (‘hi, 6) – Over her, args is treated as a tuplemap(function, l/t) Maps function to all entries in list or tuple. list()or tuple() to return as list or tuplefilter(function, l/t) Filters & keeps entries that are True in func. list()or tuple() to return as list or tupleall(l/t)

Use with map() to compare

Returns True if all entries of a list or tuple are true

all(map(function, seq)) → Returns True if all entries in seq are True in functionany(l/t)

Use with map() to compare

Returns True if any entry of a list or tuple is true

any(map(function, seq)) → Returns True if any entry in seq is True in functionmax(l/t), min(l/t) Returns highest, lowest value in a list or tuple (See left for dictionary)

zip(*arg)

>> list(zip([1,2,3,4],[1,2,3]))

>> [(1,1),(2,2),(3,3)]

Combines elements in corresponding indices of a mixture of lists, tuples, or ranges

arguments into one tuple group per index. Stops at length of shortest argument.

Use this to transpose a matrix → [list(row) for row in zip(*mat)][sum(i) for i in list(zip(*l))] → Sums up l index-wise and returns sequence of sumsUse list comprehension to change each entry to list since default is tuple

for x,y,… in zip(*arg)Loops through a mixture of lists, tuples, or ranges and stops at the length of the

shortest argumentset(t/l) Removes repeats. Use with list()or tuple() to return as list or tuplex.count(i) Returns number of occurrences of i in x

Useful String Functions *Space is included as a character in a stringCommand Result

s.digit() Returns True if s is an integers.isalpha() Returns True if s is a letter/word. Spaces return Falses.replace(old, new, *number) Replaces all occurrences of old with new, unless a specified number is givens = s.join(iterable) Joins all strings in iterable, separated by s. Use s = ‘’ to convert iterable to strings.lower()/s.upper() Changes all characters in s to lowercase/uppercases = ''.join(sorted(list(s))) Sorts a stringlst = s.split() Splits a string at space into a listtuple(s) Returns tuple of individual characters in slist(s) Returns list of individual characters in s

Useful Number FunctionsCommand Result

round(float, *decimals) Rounds a float to the given number of decimal place, if not, nearest integerabs(num) Returns absolute value of a number[int(dig) for dig in str(num)] Splits a number into individual digits as entries in a listfrom math import ceil

ceil(float)Returns ceiling of float

Page 2: Comparison Operations Types Integer Float String Bool(1/0 ...Use this to transpose a matrix →[list(row) for row in zip(*mat)] [sum( i) for in list(zip(*l))] →Sums up l index-wise

Python Loops

RecursionIteration

For loop While loop

Use it for problems that have some kind of pattern involving a recursive formula. Need to be able to find a base case/null value.

e.g. fib(n) = fib(n-1) + fib(n-1) Base case: f(1), f(2) = 0,1fact(n) = n * fac(n-1) Null value: f(0) = 1

Use it for problems that can build up on the previous value stored in a variable. Similar to recursion, and it’s better to use this, unless there is a clear recursive formula.Use it if you need to iterate through a set (str/tup/range()).

Iterating through range() using numbers can be used as a counter or to access the numbers.Similarly, iterating through str/tup can be used as a counter for len(str/tup) or used to access the values.

break Terminates the current loop and resumes execution at the next statementcontinue Rejects all the remaining statements in the loop and returns to the top of the loop

def <fn> (param):if param == <terminating value>:

return <null value>else:

return <recursive call using fn and some value if needed>

def <fn> (param):<result>for element in

<str/tup/range(start,stop,step):<do whatever you want with result>

return result

def <fn>(param):<result><counter>while <condition>:

<do what you want with result><increment counter>

return <result>*These are just some examples. The structure is usually like this but can vary depending on the need of the question.

*For while loop, some sort of a counter is needed for the loop to progress, else it’ll be an infinite loop.Order of Growth for Loops

Draw recursion tree

For iterative solutions,

Time Complexity is the number of times iterated, usually O(n). Space Complexity is usually O(1) as memory is recycled for next value** LOOK AT THE ITERABLE TO DETERMINE

** UNLESS IN THE CASE OF TUPLES (IMMUTABLE), AND A NEW TUPLE MUST BE CREATED, TIME AND SPACE COMPLEXITY MAY BE len(tuple)

Time Complexity:Number of nodes at each level

e.g. F(n): Binary Tree is O(2n)

Space Complexity:Height of tree

e.g . F(n) has n recursions – O(n)

STRING/LIST/TUPLE SLICING TAKES UP O(n) TIME. FACTOR IT IN!DICTIONARY LOOKUP HAS O(1) RUNTIME

Some Other Functions

Count Leaves, Is leafCounts the number of leaves in a tree

Merge sort Binary Search

def is_leaf(item):return type(item) != tuple

def count_leaves(tree):if tree == ():

return 0elif is_leaf(tree):

return 1else:

return count_leaves(tree[0]) + count_leaves(tree[1:])

def merge_sort(lst):if len(lst) < 2:

return lstmid = len(lst)//2left = merge_sort(lst[:mid])right = merge_sort(lst[mid:])return merge(left, right])

def binary_search(key, seq):def helper(low, high):

if low > high:return False

mid = (low + high)//2if key == seq[mid]:

return Trueelif key < seq[mid]:

return helper(low, mid-1)else:

return helper(mid+1, high)return helper(0, len(seq)-1)

Scale TreeApplies map to a tree, retaining the tuple

Merge

def scale_tree(tree, factor):def scale_func(subtree):

if is_leaf(subtree):return factor * subtree

else:return scale_tree(subtree, factor)

return map(scale_func, tree)

def merge(left, right):results = []while left and right:

if left[0] < right[0]:results.append(left,pop(0))

else:result.append(right.pop(0))

results.extend(left)results.extend(right)return results

Enumerate Tree - Flattens a tree Signal Processing Technique

def enumerate_tree(tree):if tree == ():

return ()elif is_leaf(tree):

return(tree,)else:

return enumerate_tree(tree[0]) + enumerate_tree(tree[1:])

def sum_odd_squares(tree):return \accumulate(add, 0,

map(square,filter(is_odd,

enumerate_tree(tree))))

Object Oriented Programming Multiple Inheritance And Diamond inheritance

class ClassName:def __init__(self, name, ..., *args #if there are arbitrary inputs):

self.name = name…self.arbitary_inputs = args #Don’t put star here. This gives a tuple. Use list() if needed

def method(self, *args #if there are arbitrary inputs):print(‘hello’)

class ClassName(parent class if inheriting, *multiple parent classes are allowed):def __init__(self, name, ..., *args #if there are arbitrary inputs):

super().__init__(name, ..., *args if there are arbitrary inputs) #args to inherit#Do not add attributes being inherited from parent! #Unless its being modified, or the child class has additional attributes…self.arbitary_inputs = args #Don’t put star here. This gives a tuple. Use list() if needed

def method2(self, *args #if there are arbitary inputs):print(“hi”)return super().method(*args)

- A class can inherit properties, attributes, and methods from a parent class.

- The child class can also have its own version of the same method (Method Overloading), and these methods can also reference and call other classes’ versions of the same method (Method Overriding).

- The child class can also have its own attributes and methods.- When a child class is created with multiple parent classes,

order takes precedence. Method resolution order is the order that Python follows to look for a method in parent classes.

- Python will look at all child classes to find a method before moving onto the final parent class.

OOP Tips

- Use isinstance(object, Class) to determine if an object is of class Class. Will work with parent class too.

- In defining a method in a child class, use the parent method as much as possible. Once you have edited the method, return super().<method>(*args) if you are using the parent method

- To access an attribute, <name of object>.<attribute>- To access a method, <name of object>.<method>(*args)- A child class will inherit everything from its parents, even attributes that aren’t in

super().__init__(here)

Handling Exceptions

Exception handling syntax

try: #tries statement to see if it worksstatement

except: #catches all errorsstatement

except <ErrorType>: #only catches this typestatement

except (<ErrorType1,<ErrorType2>,<ErrorType3>): #catches first errorstatement

except ErrorType as err: #catches and stores Error as err to reuseraise SomeOtherErrorType(str(err))

else: #only executes if there are no exceptionsstatement

finally: #always executesstatement

Raising Exceptions

Raising exceptions allows the programmer to force a specific exception to occur.

User-defined Exceptions

To create an error class,

class <name_of_error>(Exception):def __init__(self, name, msg, …): #arguments depend on context

super().__init__(msg) #inherits from base Exception classself.name = name

To call on this error, or use this error in a code, create an instance of<name_of_error>(*arguments as necessary) in the code, and raise it

Example:

class EvolveError(Exception):def __init__(self, pokemon, msg):

super().__init__(msg)self.pokemon = pokemon

def evolve(self):if not self.evolutions:

raise EvolveError(self, self.name + " cannot evolve further")

Common types of Errors

Name Meaning Examples

SyntaxError Incorrect or improper structure of the code

print ‘no bracket’

Common types of Exceptions

AttributeError Raised when attribute assignment or reference fails.

(1,2,3).append()#Tuple cannot append[1,2,3].apppend()#What is apppend?

IndexError Raised when index of a sequence is out of range.

lst = [1,2,3]lst[3]#There is no index 3

KeyError Raised when a key is not found in a dictionary.

d = {1:2, 3:4}d[5]#There is no key 5

NameError Raised when a variable is not found in local or global scope.

print(a)#What is a?

RuntimeError Raised when an error is detected that doesn’t fall in any of the other categories.

The associated value is a string indicating what precisely went wrong.

TypeError Raised when a function or operation is applied to an object of incorrect type.

int([1,2])#You can’t change a list to an intDICT KEY IMMUTABLE

UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.

ValueError Raised when a function gets argument of correct type but improper value.

int(“hi”)#You can’t change “hi” to an int

ZeroDivisionError Dividing a number by zero 5/0

*TypeError is raised when a wrong datatype is passed into a function or operation, but ValueError is raised when the correct datatype is passed, but the value of the data cannot be evaluated by the function.

Message Passing

def make_stack(): stack = []count = 0

def helper(msg, val=None):nonlocal count if msg == "push“:

stack.append(val) elif msg == "peek":

return stack[-1] elif msg == 'pop':

return stack.pop() elif msg == 'size':

return len(stack) return helper

How does this work?

new_stk = make_stack()- Creates a stack called new_stk

stk(‘push’, 2)- Same as make_stack()(‘push’, 2)- Since make_stack takes in no argument, (‘push’, 2) moves to helper- return helper(‘push’, 2)- helper is defined to accept 1 or 2 variables. In the case where val is not provided, helper() doesn’t raise an error as val = None sets default to None- Use *arg for multiple argumentsBUT THIS WILL BE A TUPLE- count can be used as a tracker, and nonlocal count refers to the variable outside of scope

Extra Stuff

Appending a list to itself will create a recurring list. a = [1,2]a.append(a) or a + [a] = [1, 2, [1, 2, [1, 2, …] = [1, 2, […]]

In a function, using x = x + [lst] creates a new list, while x += [lst] modifies the old list.

print(1, 2, 3, …)>>> 1 2 3 …

Adding/removing items from a dictwhile iterating through it Runtime Err