[go: up one dir, main page]

0% found this document useful (0 votes)
41 views2 pages

cs1010s Cheatsheet Midterms 2

Computer Science cheatsheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views2 pages

cs1010s Cheatsheet Midterms 2

Computer Science cheatsheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Datatypes Operators Variable Assignment Indexing and Slicing

Types Examples Types Elements Variables can be assigned to any datatype Index - str/tup[i] Slice - str/tup[start:stop:step]
Integers 1 2 3 Calculation ** * / // + - % e.g. Start  Index to start
Floats 1.0 2.1 3.001 Comparison > >= < <= == != is x=5 x = 0.5 string1 = ‘hello!’ tuple2 = (1,2,3) Index to stop
returns i-th Stop 
Strings ‘ ‘ / “ “ ‘Cs1010s!’ ‘’ / “” Truth Table (non-inclusive)
index of str/tup
Multiple Variable Assignment (Single Line) Number of Indices to skip
Booleans True (1) False (0) AND TRUE FALSE OR TRUE FALSE NOT Step 
Use this to replace values at the same time If negative, slice in reverse
Tuples (1,2,3) (1, True, ‘a’) () TRUE TRUE FALSE TRUE TRUE TRUE Negates If [start or stop ≥ len(str/tup)]
e.g. If i ≥ len(str/tup)
* When compared, Bool become 1/0 FALSE FALSE FALSE FALSE TRUE FALSE bool/is/in or [stop < start and step > 0]
x, y = 1, 2  Index Error
x, y = y, x  x and y values are swapped  No error, slice returned even if empty
Arithmetic Operations
x = 2, y =1
Types Integer Float String Bool(1/0) Tuple Forward
0 1 2 3 4 5 6 7 8 9
Integer ** * / // + - % ** * / // + - % * ** * / // + - % * Assignment Operator Index
Float ** * / // + - % ** * / // + - % * ** * / // + - % * Operator Example, variable is x Equivalent to str/tup a b c d e f g h i j
String * * + * = x=5 x=5 Reverse
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
+= x += 5 x=x+5 Index
Bool(1/0) ** * / // + - % ** * / // + - % * ** * / // + - % *
Tuple * * * + -= x -= 5 x=x-5
How to slice with negative indices? Same as positive.
*= x *= 5 x=x*5 Use reverse index (or convert to forward index) and read from Start Index to
Comparison Operations
/= x /= 5 x=x/5 End Index.
Types Integer Float String Bool(1/0) Tuple * Stop is non-inclusive for negative indices as well!
%= x %= 5 x=x%5
Integer > >= < <= == != > >= < <= == != == != > >= < <= == != == !=
//= x //= 5 x = x // 5
Float > >= < <= == != > >= < <= == != == != > >= < <= == != == != Types of Functions
**= x **= 5 x = x ** 5
String == != == != > >= < <= == != == != == != Functions with a name Anonymous (lambda) functions
Can be used for a variable assigned to any datatype, as
Bool(1/0) > >= < <= == != > >= < <= == != == != > >= < <= == != == != def <fn> (params): <assign> = lambda params: desired result
long as the Arithmetic Operation is valid for that type
Tuple == != == != == != == != > >= < <= == != <code if necessary> e.g.
Variable Scoping return desired result square = lambda x: x**2
is/is not can be used where ==/!= can be used but is/is not compares identity while ==/!= compares equivalence
Numbers (int, flt, and bool) Letters tup and str
Variables modified within a function do not alter the e.g. square(2) = 2**2 = 4
Compared numerically Uppercase letters < Lowercase letters Compare the first non-equal values global variable
def square(x):
** Value of str(number) < str(letter) Value increases down the alphabet Else, compare by size >>> x = 5 #global variable
return x**2 * If an assignment can stand on its own
>>> def square(x):
Type Conversions square(2) = 2**2 = 4 without (), it is most likely a lambda function
return x*x
Integer Float String Bool Tuple Value inputted will replace the params found in desired result
>>> square(x)
Only for int strings 1 if True Value inputted can be a function as well.
int() No change Floor of float Not possible 25
Turns strings to integers 0 if False Functions are always evaluated leftmost, innermost.
>>> x
Only for float strings 1.0 is True
float() float(5) = 5.0 No change Not possible 5 #remains unchanged Conditional Statements
Turns strings to floats 0.0 if False
Structure: One block
‘True’ if True Membership Tesing
str() str(5) = ‘5’ str(5.0) = ‘5.0’ No change str((1, 2)) = ‘(1, 2)’ if <condition>: Always the first statement. Will evaluate if true.
‘False’ if False in  check if a str in a string or an int/str in a tuple <result> “if” statements will start a new block.
True if not empty True if not empty ‘a’ in ‘apple’  True ‘h’ not in ‘hi’  False Can have multiple elif statements.
bool() True True No change elif <condition>:
False if empty False if empty ‘a’ not in (‘a’,’b’)  False 1 in (1,2)  True Will evaluate if true. Not necessary.
tuple() Not possible Not possible tuple(‘A1’) = (‘A’, ’1’) Not possible No change **1 in ‘cs1010s’  Error **‘1’ in ‘cs1010s’  True <result>
Final Statement. Not necessary. Will evaluate if rest are
else:
Tuples Box and Pointer Notation false. If missing, function will just pass.
<result>
Immutable sequences. They are iterable. Slicing can be used, but a new tuple will be created Elements in tuples exist outside of the tuple.
Examples of Tuples Tuple Operations Tuple
(1, 2, 3, 4) Tuple with 4 elements Tuples can be added Tuples put in other tuples.
((1, 2), 3, 4) Tuple with 3 elements bar = (1, 2) bat = (3, 4) bar = (1, 2) bat = (3, 4)
(1,) Tuple with 1 element foo = bar + bat foo = (bar, bat)
(1) Integer, not a tuple foo  (1, 2, 3, 4) foo  ((1, 2), (3, 4)) Each box points to another tuple, or a single element
Python Loops Order of Growth Data Abstraction
Iteration *Always look at greatest value ** DO NOT BREAK ABSTRACTION
Recursion *Worse Case Scenario As much as possible, use
For loop While loop
O(1) Constant functions that have been defined
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. O(log n) Logarithmic
** DO NOT CROSS ABSTRACTION
Use it for problems that have some kind of pattern involving a Use it if you need to iterate through a set (str/tup/range()). O(n) Linear
BARRIER AND ASSUME
recursive formula. O(n log n) Linearithmic IMPLEMENTATION
Need to be able to find a base case/null value. Iterating through range() using numbers can be used as a counter or to access the numbers. O(n2) Quadratic/Binary
Similarly, iterating through str/tup can be used as a counter for len(str/tup) or used to access the For example,
O(n3) Cubic/Tertiary
e.g. fib(n) = fib(n-1) + fib(n-1)  Base case: f(1), f(2) = 0,1 values. If we “don’t know” x is a tuple,
fact(n) = n * fac(n-1)  Null value: f(0) = 1 O(2n) Exponential
you cannot add x to a tuple
break  Terminates the current loop and resumes execution at the next statement O(nn) Exponential assuming that it is
continue  Rejects all the remaining statements in the loop and returns to the top of the loop O(n!) -

def <fn>(param): Higher Order Functions


def <fn> (param): def <fn> (param): <result> Used to generalise functions and capture a programming pattern
if param == <terminating value>: <result> <counter> Can accept functions as a parameter and can return a function
return <null value> for element in <str/tup/range(start,stop,step): while <condition>:
e.g.
else: <do whatever you want with result> <do what you want with result>
return <recursive call using fn and some value if needed> return result <increment counter> f(n) that modifies term start value
return <result>
def sum(term, a, next, b):
*These are just some examples. The structure is usually like this but can vary depending on the need of the question.
if a > b: stop value
*For while loop, some sort of a counter is needed for the loop to progress, else it’ll be an infinite loop.
return 0 f(n) that increments term
Order of Growth for Loops else:
Draw recursion tree return term(a) + sum(term, next(a), next, b)
For iterative solutions,
Time Complexity:
Number of nodes at each level Time Complexity is the number of times iterated, usually O(n). previous term added new term updated
Space Complexity is usually O(1) as memory is recycled for next value Python Built-In Functions
e.g. F(n): Binary Tree is O(2n) ** LOOK AT THE ITERABLE TO DETERMINE
Space Complexity: Function Used on Returns
Height of tree ** UNLESS IN THE CASE OF TUPLES (IMMUTABLE), AND A NEW TUPLE MUST BE CREATED, abs() Numbers Absolute value of a number
TIME AND SPACE COMPLEXITY MAY BE len(tuple) – worst case scenario len() Strings, Tuples Number of elements
e.g . F(n) has n recursions – O(n)
max() Strings, Tuples Element with largest value
Map and Filter – CS1010S Versions min() String, Tuples Element with smallest value
Map Filter round() Numbers Floor of a number
map(fn, seq)  Returns a new sequence with the same operation applied to filter(pred, seq)  Returns a new sequence of elements that are True for the predicate set() Strings, Tuples List of elements w/o repetition
every element in a iterable function sorted() Strings, Tuples List of elements sorted ascendingly
map(lambda x: x+1, (1,2,3,4,5))  (2,3,4,5,6) filter(lambda x: x % 2 != 0, (1,2,3,4,5))  (1,3,5) type() Anything Datatype of the input

Some Other Functions Signal Processing Technique


Scale Tree Enumerate Tree
Count Leaves Is leaf
Applies map to a tree, retaining the Flattens a tree, keeping all elements in
Counts the number of leaves in a tree Returns True if item is a single element
tuple order into one tuple
def count_leaves(tree): def is_leaf(item): def scale_tree(tree, factor): def enumerate_tree(tree):
if tree == (): return type(item) != tuple def scale_func(subtree): if tree == ():
return 0 if is_leaf(subtree): return ()
elif is_leaf(tree): return factor * subtree elif is_leaf(tree):
return 1 else: return(tree,)
else: return scale_tree(subtree, factor) else:
return count_leaves(tree[0]) + return map(scale_func, tree) return enumerate_tree(tree[0]) +
count_leaves(tree[1:]) enumerate_tree(tree[1:])

You might also like