-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelected Notes.txt
20 lines (20 loc) · 17.2 KB
/
Selected Notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#separator:tab
#html:true
List Comprehension in Python "List Comprehension enables you to create new lists without a for-loop iterator. <br><br>cities = [""NYC"", ""LA"", ""NOLA"", ""SF""]<br>newlist = [x for x in cities if ""a"" in x] = [""LA"", ""NOLA""]<br>newlist = [x for x in cities if x != ""NYC""]<br>newlist = [x for x in range(10)]<br>newlist = [x.upper() for x in cities]<br>newlist = ['hola' for x in cities]<br>newlist = [x if x != ""NOLA"" else ""Chicago"" for x in cities] #replace ""NOLA"" with ""Chicago"" in output<br><br>print(newlist)"
Python Basics "print(""Hello World!"")<br>lines in the same block of code should be indented with the same number of spaces; indentation issues<br># Line Comment<br><br>""""""""<br>Block Comment<br>""""""<br>"
Variables Types in Python "var = ""hello"" # <b>str</b>, immutable<br>print(type(var)) # prints ""<class 'str'>""<br>#using double or single quotes to initialize strings has same behavior<br><br>var = 10 # <b>int</b>, immutable<br>print(type(var)) # prints ""<class 'int'>""<br><br>var = 10.0 # <b>float</b>, immutable<br>print(type(var)) # prints ""<class 'float'>""<br><br>var = True # <b>False</b>; Bool, Immutable - note CAPITALIZED<br>print(type(var)) # prints ""<class 'bool'>""<br><br>var = (8,9) # <b>tuple</b>, immutable, collections of objects<br>print(type(var)) # prints ""<class 'tuple'>""<br><br>var = [1, 2, 3] # list<br>print(type(var)) # prints ""<class 'list'>""<br><br>var = None # None; replaces null<br>print(type(var)) # prints ""<class 'NoneType'>""<br><br>Variables can be cast to different types repeatedly<br>Variable names are case-sensitive\<br><br>Assign values to multiple variables: <br>a, b, c = ""I"", ""love"", ""CS221""<br>print(a, b, c) # I love CS221<br>"
Int/Float/Bool Operations in Python "var = 10<br>print(var + 4) // print(var - 4) // print(var * 4)<br><br>Exponentiate: print(var ** 4)<br><br>Float division: print(var / 4) \\\\\\\\ Integer division: print(var // 4)<br>integer division is the same as dividing then casting, i.e. print(int(var / 4))<br>Compound operators: var **= 4 \\\\\\ var += 1<br>No increment or decrement using ++, -- in Python<br><br>print(not True) # prints False<br>print(True and False) # prints False<br>var = True or False<br>print(var) # prints True<br><br>== checks value equality, != checks inequality, <= checks lequal, >= checks grequal<br>These things will evaluate to BOOL values, i.e. a <= b evaluates either true or false<br>"
String Operations in Python "<ul><li><b>Comparison: </b>a = ""221""; b='221'; print(a >= b); #returns True</li><li><b>Length: </b>a= ""I love CS221!""; print(len(a)) #prints 13</li><li><b>Element-Index:</b> print(a[0]) #prints ""I"" \\\\\\\\ print(a[2:6]) #prints ""love"" (end-exclusive)</li><li><b>To Lower/Upper</b>: print(a.lower()) #prints ""i love cs221!""</li><li><b>Multiply:</b> print(a * 4) #prints I love CS221!I love... 4 times</li><li><b>Concatenate:</b> b = ""hbu?""; c = a + "" "" + b; print(c) #prints ""I love CS221! hbu?""</li><li><b>Contains</b>: print(""love"" in a) #True \\\\ print(""love"" not in a) #False \\\\ print(a.index(""love"")) #2</li><li><b>Split/Substring: </b>print(a.split()) #prints ['I', 'love', 'CS221!'] or print(a.split('2')) #prints ['I love CS', ' ', '1!'] </li><ul><li>The input here is the delimiter; the default delimiter is a space when input left blank</li><li>When the input here is 2, the empty string returned is the string <i>between</i> the delimiters</li></ul><li><b>Split & combine a list:</b><br></li><ul><li>a_splitted = a.split()</li><li>print(a_splitted) # ['I', 'love', 'CS221!']</li><li>a_joined = ' '.join(a.splitted)</li><li>print(a_joined) # I love CS221!</li></ul><li><b>Format/Dynamically call variables</b> into strings</li><ul><li>pi = 3.14159</li><li>print(""Pi is %.2f!""%(pi)) #Pi is 3.14! #""print me two decimals of pi as a floating point</li><li>print(f""Pi is {pi}!"") #Pi is 3.14159! #f in front of string will refer to curly brackets & replace with variable</li><li><br></li></ul></ul>"
Control Flows & Conditionals in Python "<ul><li><b>for-each loops for strings, arrays</b></li><ul><li>for char in s/arr: #each char new line of print</li><ul><li>print(char)</li></ul><li>for i, char in enumerate(a): #chars now have line numbers in output</li><ul><li>print(i, char) </li></ul></ul><li><b>discrete for loops:</b></li><ul><li>for i in range(4): #same as for(int i=0; i<4; i++)</li><ul><li>print(i)</li></ul><li>for i in range(2, -3, -2): #same as for(int i=2; i> -3, i = -2)</li><ul><li>print(i)</li></ul></ul><li><b>While loops</b></li><ul><li>ind = 0</li><li>while ind < 5:</li><ul><li>print(ind)</li><li>ind+=1</li><li>break #ends the loop</li></ul></ul><li>If condition:</li><ul><li>If-Else</li><ul><li>if str == ""example"":</li><ul><li>do smth</li></ul><li>elif str == ""example2"":</li><ul><li>do smth else</li></ul><li>else:</li><ul><li>do 3rd thing</li></ul></ul><li>if None</li><ul><li>a = None</li><ul><li>if a: </li><ul><li>#do smth</li></ul><li>else: <br></li><ul><li>print(""None"")</li></ul></ul><li>arr = [ ]</li><ul><li>if arr: \\\\ else:</li></ul><li>str = ' '</li><ul><li>if str: \\\\\\ else:</li></ul><li>if a is None: print('yes')</li></ul></ul></ul>"
Functions/Mutability/Variables/Scope/Recursion in Python "def func(a, b): <b>#define function</b><br>pass #filler which quiets errors<br>#call function:<br>func(5, 10)<br><br><b>#optional parameters</b><br>def check_range(a, min_val = 0, max_val=10): #create function to check if given number is in a range<br> return min_val<a<max_val<br><br>check_range(5, max_val=3) #call the function<br><br>#<b>immutable type parameters are passed by value. Ex:</b><br>def func(variable):<br> variable=10<br> print(variable)<br>a=15<br>print(a) #outputs 15<br>func(a) #outputs 10<br>print(a) #outputs 15<br><br><b>Mutable type parameters are passed by reference. Ex:</b><br>def func(variable):<br> variable[0] = 10<br> print(variable)<br>a=[0,1,2,3,4]<br>print(a) #[0,1,2,3,4]<br>func(a) #[10,1,2,3,4]<br>print(a) #[10,1,2,3,4]<br><br><b>#circumvent mutability by creating a deep copy of your variable for your function:</b><br>def func(var):<br> #alt 1<br> var = var[:]<br> #alt 2<br> var=copy.deepcopy[variable]<br> var[0]=10<br> print(var)<br>a = [0,1,2,3,4]<br>print(a) #[0,1,2,3,4]<br>func(a) #[10,1,2,3,4]<br>print(a) #[0,1,2,3,4]<br><br><b>#functions can access variables in their parent block's scope</b><br>outside_var=""This is an outside variable!""<br>def func():<br> print(outside_var)<br>print(outside_var)<br>func()<br><br><b>#functions can't change variables in their parent block's scope unless using the global key</b><br>outside_var = ""This is an outside variable!""<br>def func():<br> global outside_var<br> outside_var = ""Function changed the outside variable!""<br>print(outside_var) #""This is an outside variable!""<br>func()<br>print(outside_var) #""Function changed the outside variable!""<br><br><b>#if a same-name variable is function-scoped, the later definition overwrites the former only in that scope</b><br>var=""outside var!""<br>def func(var=""func var""):<br> print(var)<br>print(var) #outside var!<br>func() #func var<br>print(var) #outside var!<br><br><b>#variables defined in function scope can only be accessed outside using global key(bad form):</b><br>def foo():<br> global global_var #if you printed after this line, undefined error<br> global_var=""This is global var!""<br> print(global_var)<br>def bar():<br> print(global_var)<br>foo() #This is global var!<br>bar() #This is global var!<br><br><b>#Defining functions within functions:</b><br>def main_function(a):<br> def helper_func(a):<br> return int(a)<br> print(a)<br> b=helper_func(a)<br> print(b)<br><br>main_function(2.0) <br>#2.0<br>#2<br><br><b>Functions taking functions as variables:</b><br>def function_taker(a, func):<br> return func(a)<br><br>function_taker(1.0, int) #1<br><br><b>Separately define passed function:</b><br>def parameter_function(x):<br> return x+5<br>def function_taker(a, func):<br> return func(a)<br>function_taker(1.0, parameter_function) #6.0<br><br><b>#Lambda functions:</b><br>def function_taker(a, func):<br> return func(a)<br>function_taker(1.0, lambda x: x + 5) #6.0<br><br><b>lambda functions can use variables in their parent's block scope:</b><br>num_to_add = 10<br>def function_taker(a, func):<br> return func(a)<br>function_taker(1.0, lambda x: x + num_to_add) #11<br><br><b>Recursive functions:<br></b>def print_positive_numbers(num):<br> if num <= 0:<br> print(""Done!"")<br> else:<br> print(num)<br> print_positive_numbers(num-1)<br><br>print_positive_numbers(10) # prints positive numbers counting down from 10 one at a time<br><br>#can also inherit classes:<br>class Bar(Foo):<br> passs<br><br>obj = Bar(3)<br>obj.print_x() #3<br>"
Classes in Python "class Foo: #if ""class Foo(object): all python classes will inherit 'object'<br> class_variable = 'same'<br> def __init__(self, x): #optional constructor; required for some classes<br> self.x = x #first parameter ""self"" for instance reference, like ""this"" in java<br> def print_x(self): #instance reference is required for all instance variables<br> print(self.x)<br> @classmethod<br> def modify_class_variable(cls):<br> cls.class_variable = 'changed'<br> @staticmethod<br> def print_hello():<br> print(""Hello!"")<br><br>print(Foo.class_variable) #same<br><br>obj1=Foo(6) <br>obj1.print_x() #6<br>print(obj1.class_variable) #same<br><br> obj2 = Foo(5) <br>obj2.print_x() #5<br>print(obj2.class_variable) #same<br><br>obj1.modify_class_variable()<br>print(obj1.class_variable) #changed<br>print(obj2.class_variable) #changed<br>print(Foo.class_variable) #changed<br><br><br><b>Classes can also be inherited:<br></b>class Bar(Foo): #inherits variables and methods from above class<br> pass<br><br>obj = Bar(3)<br>obj.print_x() #3"
SciPy "<pre><code>>>> from scipy.stats import poisson, binom
>>> n, p, lamb = 5, 0.5, 1
>>> poisson(lamb).pmf(0)
0.36787944117144233
>>> binom(n, p).pmf(1)
0.15624999999999994
>>></code></pre>"
Iterables in Python "#immutable iterables, fixed size <br>astring = str()<br>atuple = tuple()<br><br>#mutable iterables, not fixed size<br>alist=list() #linear<br>adict = dict() #Hash table, stores (key, value) pairs<br>aset = set() #hash table, like dict but only stores keys<br><br>#any iterable gives size with len(iterable)<br>print(len(alist)) #0<br><br>alist = [ ] #initialize empty,, equivalent to list()<br>alist = [1, 2, 3, 4, 5] #initialized list<br><br>#access & modify elements:<br>print(alist[0]) #1<br>alist[0] = 5 <br>print(alist) #[5, 2, 3, 4, 5]<br>print(""-""*10)<br>print(alist[-2]) #get last element at index len-1 #prints 4<br>print(alist[3:]) #get elements starting from index 3, inclusive #prints [4, 5]<br>print(alist[:3]) #get elements stopping at index 3, exclusive #prints [5, 2, 3]<br>print(alist[2:4] #get elements within index range [2, 4] #prints [3, 4]<br>print(alist[len(alist):]) #prints nothing, index out of range #prints [ ]<br><br>#reverse a list<br>alist[::1] # returns [5, 4, 3, 2, 5]<br><br>#list methods:<br>alist.append(""new item"") #insert at end<br>alist.insert(0, ""new item"") #insert at index 0<br>alist.extend([2, 3, 4]) #concatenate lists; equivalent to alise += [2, 3, 4]<br>alist.index(""new item"") #search by content<br>alist.remove(""new item"") #remove by content<br>popped = alist.pop(0) #remove by index<br>print(alist) #[2, 3, 4, 5, 'new item', 2, 3, 4]<br>print(popped) #5<br><br><br>#if list contains element:<br>if ""new item"" in alist:<br> print(""found)<br>else:<br> print(""not found"")<br>#found"
Tuples in Python "immutable, hashable(can be used as dict key) lists of fixed size; no insertion or deletion<br>atuple = (1,2,3,4,5)<br>atuple = (1,) #need comma for singleton atuple, otherwise defaults to integer<br><br>#index/traverse same as list<br>atuple=tuple([1,2,3])<br><br>#use as dictionary keys<br>ngram = (""a"", ""cat"")<br>d = dict()<br>d[ngram] = 10<br>d[ngram] += 1<br><br>#named tuples improve readability<br>from collections import namedtuple<br>Point = namedtuple('Point', 'x y')<br>pt1 = Point(1.0, 5.0)<br>pt2 = Point(2.5, 1.5)<br>print(pt1.x, pt1.y) #1.0 5.0"
Dictionary in Python dict; defaultdict; counter; set "store key-value pairs; not hashable; dynamic size; no duplicates allowed<br>Hash-table implementation makes searching fast<br><br>adict = { } #same as dict()<br>adict = {'dog': 10, 'bird': 5, 'lion': 8}<br>print(adict) #{'dog': 10, 'bird': 5, 'lion': 8}<br><br>print(adict.keys()) #dict_keys(['dog', 'bird', 'lion'])<br>print(adict.values()) #dict_values([10, 5, 8])<br>print(adict.items()) #dict_items([('dog', 10), ('bird', 5), ('lion', 8)])<br><br>#access by key<br>print(adict['lion']) #8<br><br>#check if key exists<br>adict['tiger'] #throws error<br>if 'tiger' in adict:<br> print(adict[key])<br>else:<br> print(""key not found"") # key not found<br><br>#insert new keys<br>adict['tiger'] = 1<br><br>#modify existing<br>adict['lion'] = 20<br><br>#traverse dictionaries<br>for key in adict:<br> print(key, adict[key])<br>#dog 10<br>#bird 5<br>#lion 8<br>#tiger 1<br><br>Traverse key-value pairs together<br>for key, val in adict.items():<br> print(key, val) #same output as above lol<br><br>#DefaultDict is a special dictionary returning a default value when a queried key doesn't have one to match.<br>from collections import defaultdict<br>adictr = defaultdict(int)<br>adict['cat'] = 5<br>print(adict[cat]) #5<br>print(adict[dog]) #0<br><br>#you can also pass a custom function:<br>from collections import defaultdict<br>adict = defaultdict(lambda: 'unknown')<br>adict['cat'] = 'feline'<br>print(adict['cat']) #feline<br>print(adict['dog']) #unknown<br><br>#counters are dicts with default value 0.<br>from collections import Counter<br>counter1 = Counter()<br>counter1['t'] = 10<br>counter1['t'] += 1<br>counter1['e'] += 1<br>print(counter1) #Counter({'t' : 11, 'e' : 1})<br><br>#initialize counters from other iterables:<br>counter2 = Counter(""letters to count"")<br>print(counter2) # long output but it logs all letters with corresponding counts<br><br>#operations between counters<br>print(""1"", counter1 + counter2) # prints 1, then sum of both letter counts together<br>print(""2"", counter1 - counter2) #prints 2, then Counter({'t': 7}), the difference between the two sets<br>print(""3"", counter1 or counter2) #or for union, and for intersection<br><br>#last Counter Methods<br>counter2.most_common(5) #prints 5 most common values of that counter plus keys<br>for k, v in counter2.most_common(5):<br> print(k, v)<br><br><br>#Set is special dictionary without values & no repetitions<br>aset = set()<br>aset.add('a')<br>alist = [1,2,3,3,3,4,3]<br>alist = list(set(alist))<br>print(alist) #[1,2,3,4]"