WarGame
An introduction to intermediate Python
Today
Git Setup
Download Git
Mac and Linux users should have a tool called “git” in their command line.
Windows users need https://git-scm.com/downloads to get Git Bash shell.
We’ll wait until next week for git commands.
Git Install for Windows
https://git-scm.com/downloads
Reviewing our Python
Table of Contents
- Dictionaries
Intro to Dictionaries
>>> cnc = {}
>>> cnc["Key"] = "Value"
>>> cnc
{'Key': 'Value'}
>>> cnc["Key"]
'Value'
Sets
Remember lists are ordered
Sets are not and do not have duplicates.
>>> rocket = ["r", "a", "c", "c", "o", "o", "n"]
>>> rocket
['r', 'a', 'c', 'c', 'o', 'o', 'n']
>>> set(rocket)
{'o', 'n', 'a', 'c', 'r'}
Static Methods
class Student:
def action(self):
self.describe(argument_value)
@staticmethod
def describe(arg):
print(f"No access to the self / cls variable but we have {arg}!")
Acts like functions but cleaner!
Exceptions
How to fail well.
Table of Contents
- Basic exceptions
Basic Exception
try:
print(“a”)
1 / 0
print(“b”)
except:
print(“error!”)�>>> a�>>> error!
Looks like “break” or “return”.
Else
try:
1 / 0
except:
print(“error!”)
else:
print(“success!”)��>>> error!
else:
Only runs when no error was found in the try block (we reach the end successfully).
Finally
try:
1 / 0
except:
print(“error!”)
else:
print(“success!”)�finally:
print(“finally!”)
>>> error!�>>> finally!
Finally:
Always runs no matter what happens (success or failure). Unless the computer is literally powered off.
Exception Types
try:
{}[‘a’]
except ValueError:
print(“a”)
except KeyError:
print(“b”)
else:
print(“success!”)
>>> b
We can specify the type of exception to catch.
ValueError -> e.g. 1/0
KeyError -> Bad key
Exception Types
try:
{}[‘a’]
except ValueError:
print(“a”)
else:
print(“success!”)
KeyError exception raised.
except:
-> accepts all exceptions
Otherwise we’ll get an error for uncaught exceptions.
Raising Exceptions
try:
raise ValueError()
except ValueError:
print(“a”)
else:
print(“success!”)
>>> a
We can also do this manually.
Advanced Exceptions
class InvalidTimeException(Exception):
pass
try:
raise InvalidTimeException()
except:
...
We can define custom exceptions too using inheritance.
More advanced usage might include defining constructors for our custom exception or passing arguments.
e.g. InvalidTimeException(data)
Web Intro to Git
Guide recycled from previous project. Exact links and paths will not match.
Step 1 - Go to Repo
Step 2 - Click Fork
Step 3 - Go to the bots folder (files should be visible)
Step 4 - Click “Create new file” and paste your source code (or edit)
Step 5 - Save your changes; a commit appears
Step 6 - Click pull request then “Create pull request”
Step 7 - Optional comment and then submit
Bonus Material
(Co-op prep/ Advanced CS)
Table of Contents
- Algorithms
- Multithreaded code
- Databases
- Networking
Algorithmic Questions
Know your data types.
Helpful
Start with a solution which works. Then try to optimize.
Decide whether to sort a list.
Binary search is O(log n) time.
e.g. You have two lists A and B. Find all unique elements in A not in B.
CS 341 - Algorithms in 3 minutes
Multiple strategies you can try
Divide and conquer
Greedy algorithms
Dynamic programming
CS 341 - Recursion
Recursive
Fib(n)
If n < 2
Return 0
Return Fib(n - 1) + Fib(n - 2)
Runtime? Exponential.
CS 341 - Dynamic Programming
Iterative
Cache = {}
Cache[0] = 0
Cache[1] = 0
Fib(n)
For i from 2 to n
Cache[i] = Cache[0] + Cache[1]
return Cache[n] //Runtime? Linear!
CS 350 - Operating Systems (Two Programs)
Program 1�print(“a1”)
print(“b1”)
print(“c1”)
Program 2�print(“a2”)
print(“b2”)
print(“c2”)
Programs run top-down one line at a time.
When running multiple programs the OS will pause and resume at arbitrary points.
E.g.
a1, b1, a2, c1, b2, c2
CS 350 - Operating Systems (Two Threads)
Thread 1�A = 0
A = 100
Thread 2
B = A + 10
A = B
A program (process) can run more than one thread at once.
Threads will often share variables. This can cause new kinds of bugs.��Why?
So we don’t freeze when waiting for
a task.
E.g.
Which possible final A values can we find?
A = 10, 100, 110, crash (if A not defined)
CS 350 - Operating Systems (Locks)
Thread 1�A = 0�lock.acquire()
A = 100
lock.release()
Thread 2
lock.acquire()
B = A + 10
A = B
lock.release()
A lock is a special type of variable.�It can only be acquired at most once. Otherwise the thread must wait.
E.g.
How many possible final A values can we find?
A = 10, 100, 110, crash
CS 348 - Databases
A database stores tables. (Like a folder)
A table is like a spreadsheet with a specific format.
Columns
Rows / Records
CS 348 - Why Databases?
Quickly search by criteria.
E.g. select name from students where GPA > 50;
We retrieve every value for name where the row’s GPA is greater than 50 in the students table.
Redundancy / Replication (spread data across multiple computers)
Speed (there are many many optimizations at work, b-trees, indexing, partitions, etc)
CS 456 - Networking
We need to send data between two programs.�Protocols exist at different levels of abstraction.
e.g. HTTPS for websites is built on top of a layer of TCP.
There are two common “low-level” protocols, TCP and UDP.
TCP vs UDP
TCP
Will guarantee the message arrives.
Will guarantee ordering. Will not receive a packet until all previous ones were found.
Will guarantee integrity. No corrupted data.
UDP
Only guarantees integrity. Of those that arrive.
Much faster.
Picking TCP vs UDP
TCP
Useful for chat messages or loading a website.
UDP
Useful for calls. If a millisecond of audio is corrupted, we don’t need to replay it.
So you don’t forget
Next Time
There will be no lesson next week :(
What do you want to learn next?