Show Menu
Cheatography

CS1010S Finals Cheat Sheet (DRAFT) by

NUS CS1010S Finals Cheatsheet

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Types of Errors and Examples

IndexError
The index of a sequence is out of range.
(1,)[1]
KeyError
Key is not found in the dictio­nary.
cs = {10:10}; cs[s]
Syntax­Error
Invalid syntaxes found in code.
print(­Hello World) (no quote marks) or for i in range(3) (no colon)
TypeError
A functi­on/­ope­ration is applied to objects of incorrect types.
(1,2) + [3,4] or "­cs" + 1010
ValueError
Function gets an argument of a correct type but improper value.
int("3.1­4")
NameError
The variable with the name is not found in the local & global scope.
del cs1010s
Attrib­ute­Error
An attribute reference or assignment fails due to incorrect data type.
(1,2).a­pp­end(3)
ZeroDi­vis­ion­Error
Second operand (denom­inator) of a divisi­on/­module operation is zero.
1/0
Recurs­ion­Error
An operat­ion­/runs out of memory.
def f(x): return x + f(x-1)
Unboun­dLo­cal­Error
A reference is made to a local variable in a functi­on/­method, but no value has been bound to that variable.
def f(x): ;z = y + x; y = 0
Runtim­eError
Can be due to many reasons. One of them being list/d­ict­ionary size changing during iteration.
a = [1, 2]; for ele in a: a.appe­nd(ele)

Defining Custom Errors

class Custom­Error:
pass

Exception Handling

try:
The code inside the try block will run until it reaches an error. Once it does, it will be handled accord­ingly by the respective exception statem­ents.
except Error:
The code inside this block will only run if the encoun­tered error is the error to be handled by this except statement.
except Exception:
The code inside this block will only run if the error has not been handled by the previous except statem­ents.
else:
The code inside the else block will only run if no errors were encoun­tered in the try statement.
finally:
The code inside the finally block will run no matter what.

For/While Loop Statements

break
Terminates the loop (once)
continue
Stops the current iteration of the loop, and goes on to the next iteration of the current loop
pass
Does nothing and continues the rest of the code inside the current iteration of the loop
 

List shallow copies (list.c­opy(), list[:])

List and dictionary functions

string.sp­lit­(sep)
Splits the string into a list by the seperator, which by default is "­".
"­CS1­010­S".s­pli­t("1­") == ["CS­", "­0", "0S]
dict.g­et(key, value)
Returns the value that is paired to the key in the dictio­nary. If the key does not exist in the dictio­nary, then it will return the value instead.
d = {"CS­":10, 10: "­S"} ; d.get(­"­CS", "NOT FUN") == 10; d.get(­"­10", "GG CS") == "GG CS"
del dict[key]
Removes the key-value pair with the indicated key in the dictio­nary. Returns a KeyError if key is not found in the dict
d = {"CS­":10, 10: "­S"}; del d[10]; d = {"CS­": 10}
sep.jo­in(­ite­rable)
Joins all the items in the iterable into a string, with the sep inbetween each item.
d = {"CS­":10, "­10":­"­S"}; " - ".jo­in(d); "CS - 10"

Passcode locking

def lock(obj, passcode):
o = obj.copy()
o.clear()
o["l­ock­ed"] = lambda x: o if x == passcode else False

def unlock­(obj, passcode):
o = obj["lo­cke­d"] (passcode)
if o != False:
obj.cl­ear()
obj.up­date(o)

Orders of Growth (OOG)

O(1) < O(log n) < O(n) < O(n log n) < O(n2) < O(2n) < O(nn)
O(1): Indexing, replacing variable name
O(log n): Constantly halvin­g/d­oubling a number (depending on direction)
O(n): Going through the whole tuple/­string (for loop/r­ecu­rsion)
O(n2): Going through the whole tuple once for each element (Usually nested for loop)
O(2n): The tree splits into 2/x number of branches for each level (Usually for recursion tree)
Sample Answer:
Time: O(n), there is a total of n recursive calls.
Space: O(n), there is a total of n recursive calls, and each call will take up space on the stack.
Time: O(n), the loop will iterate n times.
Space: O(1), no extra memory is needed because the variables are overwr­itten with the new values.

String slicing and concat­enation takes O(n) time as well

Boolean Values

False evaluates to 0; int(False) == 0, while True evaluates to 1; int(True) = 1
On the other hand, any empty string, tuple, list, dict etc ("", (), [], {}), value 0 and None all evaluates to False; bool(0­/No­ne/­"­"­/()­/[]/{}) = False, and any other expression will evaluate to True; bool(1­/-9­5/"C­S1010S is fun"­/("C­", "­S", "­S", "­U", "­C", "­K", "­S") = True

Checking data type

1. type(v­alue) == Type
2. isinst­anc­e(v­alue, Type)