Advanced
A python program is a sequence of python statements
AKA execution stack / interpreter stack
This is a stack of stack frames
a = str()
b = aThe str function creates a new empty string. This is called instantiation
These are equivalent to list monads
The following two statements are the same
[s + z for s in iterable1 for z in iterable2]
li = []
for s in iterable1:
for z in iterable2:
li.append(s+z)[x for x in range(10) if x%2 == 0]
li = []
for x in range(10):
if x % 2 == 0:
li.append(x)Namespaces are maps
Scopes of namespaces are the actual regions of text in a python program where that namespace is accessible
Functions create local namespaces when called, and those NS are forgotten when the function returns or raises an exception that isn't handled in the function
Similarly del x is really forgetting
the map from x to its object in the local NS
Scopes are checked in the following order
Assignments to names always go to the local scope,
unless you use a global or nonlocal keyword
import and def find the names of the modules/functions in
the local scope
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)Will print
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spamHere's what's happening under the hood:
do_local defines a map from the name
spam to the str object "local spam"do_nonlocal first creates a nonlocal
name called spam, and then defines a map from this nonlocal-spam to the
str object "nonlocal spam"scope_test the assignment
spam = "test spam" is assigning
non-local spam to the object "test spam" (which is really local
in the eyes of scope_test, but it's the
same name in the scope_test NS that do_nonlocal was referring to)scope_test
is referring to that non-local spamdo_globalAll data in python is represented by objects and relations between objects
Objects have
Containers are objects that contain references to other objects in their value
Numeric objects are
int, float, complex
Int
Float
Complex
and, or, not
<, >, <=, =>, ==, !=, is, is not
list, tuple, range
s[i:j] slice from i to j
s[i:j:k] slice from i to j with step k
del s[i] removes item i
s[i:j] = t
del s[i:j]
s.append(v)
s.clear removes all values
s.count(n) returns number of occurences of n
s.copy
s.pop(n) retrieve val at n+1 and remove from s
s.remove(n) remove first time n shows up
s.reverse
Mutable
[1,2,4,1]
list() is the same as []
list('abc') gives ['a', 'b', 'c']
sort(L) sorts the list in place using only <
Interestingly, tuples are actually created by commas, not parentheses. The parentheses are actually optional
(1,3,5)
1,3,5
tuple()
Immutable sequence of numbers
range(5) (0,1,2,3,4)
range(2,5) (2,3,4)
range(2,-2,-1) (2, 1, 0, -1)
Immutable
'allows embedded "double quotes"'
"allows 'single quotes' "
str()
str.capitalize capitalizes the first letter
str.lower
str.casefold like lower, but ß -> ss
str.center(4, '-') pads to size 4 with -
str.count(s, 5, 10) counts occurances of s in range
str.endswith(T) checks if ends with anything in tuple T
str.expandtabs
str.find(s, 1,2) returns location of first instance
s in S returns boolean
str.format(A,B) replaces {i} in string
str.isalpha checks if only contains letters (no spaces)
str.join
'-'.join("too") gives "t-o-o"
str
string.split()Also called 'associative arrays'. Their entries have two pieces of data each: a key and a value. The keys all have to be unique, but the values can repeat.
Dictionaries are basically SET maps:
The keys in A are distinct by assumption, but different keys can be mapped to the same value
Maps hashable things to arbitary objects
{key : value, key : value}
dict()
list(D) returns keys
D[key] returns value
del D[key]
key in D
.clear
.get(key) returns value for key
.items reutnrs key value pairs
.keys
.values
You can use dictionaries as your values in a dictionary
.keys, .value, .items are all view objects
x in dv
len(dv)
iter(dv)
set, frozenset
x in s
A.isdisjoint(B)
A < B \subset
A <= B \subseteq
x|A|B|... is x.union(A,B,...)
x & A & B... is x.intersection
x - A - B x \setmin (A \cup B)
x ^ A is xor
x.add(e)
x.remove(e)
set.clear
set
{}
set()
Frozen Set
Three types
Say this is a file circle.py
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2from circle.py import Circle
circle_1 = Circle(42)
circle_1.radius
circle_1.calculate_area()
circle_1.radius = 5If and else always act on boolean values
if reply in {'y', 'yes', 'yep'}:
These are sort of like if / else, but they actually allow you to compare things besides boolean values
match var:
case 200:
print(...)
case 324:
...
You can actually iterate over any sequence
The way that a for loop works in python is
iter( ) on whatever you're
acting the for loop on (the container)__next__, which knows how to access the elements
in the container one at a time__next__ returns a StopIteration exceptionFOR: else is executed after the loop finishes WHILE: executed after the loop condition is false
Not executed if the loop is terminated by a break
Python doesn't like nested loops.
One way to get around this is to turn any nested loops into functions
and then just use return
Lets you get subsequences of strings
[start : stop (inclusive) : step]
start : if empty, starts at 0
step : if empty, is 1
We can reverse an integer by first turning it into a string, and then reversing it, and then turning it back into an integer
int(str(x)[::-1])
DYNAMIC ARRAYS: In Python,
LISTS: Ordered. Mutable.
As a consequence, if you want to work with an element at the very beginning of the list, it will actually take a lot of time
LINKED LISTS: Ordered. Their time complexity and the way they store data is different from ordinary lists.
Elements are called 'nodes' The first node is the 'head' Each node has 2 pieces of data: the value of the node, and a reference to the next node in the list
Useful for stacks and graphs (like actual discrete graphs from math)
The beginning of a linked list has O(1) time complexity (you always know where the first node is) The end of the list has O(n), since you have to travel from the first element to get there
Insertion/deletion at a specific point is also O(n) for the same reason
Worse at element lookup than lists, since to get to element k, you have to traverse the whole list to get there
Doubly linked lists have each node also pointing backwards; that lets you traverse from the end as well, reducing the time complexity
Circular linked lists go from the final element in the list back to the first element
In order to create a linked list
If we have 2 linked lists, how do we put them together?
How do we improve this?
Time is
Space is
There's an even better way though! It's called iterative merge or bottom-up merge
QUEUES: First-in/First-out (FIFO)
STACKS: Last-in/First-out (LIFO)
GRAPHS: You can encode them with a dictionary, where the keys are the vertices, and the values are lists that contain the vertices pointed to
ENUMERATE : Takes in an array, and outputs a new array whose entries are tuples of the form (index, array[index])
[-1] gives the last element in the list
ZIP :
SET :
Use the function sorted()
This is how python handles the \input
command in Latex
A module is any python file with definitions and statements
__name__In another file you can then import the module with import
mod.funct(1)
When you try to run a module as a stand-alone script, it will try to import it, with
__main__So if you can actually add the following to your module, to make sure it executes like a script
if __name__ == "__main__":
import sys
module_name(sys.argv[1])
Returns a sorted list of strings that says all the names defined in the given module:
These are collections of modules
You can have sub-modules
import stuff, you're
essentially instantiating an object of the class stuff, which you call stuff. Then stuff.function is calling the method from the
class/module stuff.The way that it's actually implemented in python, is
ModuleTypeAlso called f-strings
Start a string with f or F, before the quotation mark
month = "January"
day = "17th"
f"Today is {month} {day}"
f-strings are expressions evaluated at run time, rather than constants
They use Abstract syntax trees, which the CPython compiler can handle very quickly
We can compare f-strings to 2 other ways of doing string formatting in Python
%-formatting: it only handles certain types (int, str, double), not tuples, etc.
str.format: it's a bit verbose, and not as readable
open() returns a file object
f = open("C:/.../thing.txt", 'r+', encoding="utf-8")
read_data = f.read()
f.close()
(r)ead, (w)rite, (a)ppend, (r+)ead and write,
f.readline()
for line in f:
print(line, end="")
f.write("whatever I want to write")
f.seek(5, whence)
whence can be (0) from beginning (1) from current point (2) from ending
Reading and writing data types of than strings to a file is tough
import json
json.dump(stuff_to_write, f)
x = json.load(f)
Errors during execution.
We can write programs that handle specified exceptions
try:
x = (int(input("Please enter a number: ")))
break
except ValueError:
print("That wasn't a number, fool.")
else:
...
finally:
...How it works:
try block are
evaluatedelse and then finallytry,
we jump to the corresponding except (if
there is one), followed by finallyIn particular, finally always
evaluates
The with keyword allows you to write
try-except-finally statements in a cleaner way
with Expression as Target:
Suite
# is the same as
manager = (Expression)
enter = manager.__enter__
exit = manager.__exit__
value = enter()
hit_except = False
try:
Target = value
Suite
except:
hit_except = True
if not exit(*sys.exc_info()):
raise
finally:
if not hit_except:
exit(None, None, None)When you execute with, it will
__enter__ and __exit____enter__ and assigns its
return value to the Target in the with statement__exit__ is invoked
__exit__These are designed to work with resources that will only be used for a fixed period of time
If you don't close resources, it risks using up all of your memory
Once you have a context manager defined, you can call it with the
keyword with
Files already have a built-in CM
with open("file.txt") as f:
data = f.read()We never need to call close, because
it's all taken care of by the CM
CMs are classes They need two methods
__enter____exit__Always read them from the bottom up (because they're based on stacks) The lines above the error in the error message are call the traceback
We can also define our own exceptions
if :
raise TypeError("We're expecting an integer")Using raise is useful, because the
traceback will point to the specific moment of the code when the
exception was raised
But it's also extremely useful to handle edge cases
it lets us write things very generally and then just shove the edge cases into exceptions
def gcd(x,y):
try:
return gcd(y, x%y)
except ZeroDivisionError:
return xThat's stunningly beautiful This also demonstrates that exceptions aren't necessarily errors
You can catalogue multiple exceptions in a single object using exception groups
excs = [OSError('error 1'), SystemError('error 2')]
raise ExceptionGroup('here are the issues', excs)You can add notes to a rased exception
excs = []
for i in range (4):
try:
...
except Exception as e:
e.add_note(f'Happened in iteration {i+1})
excs.append(e)