1 of 41

WarGame

An introduction to intermediate Python

2 of 41

Today

  • Review some key concepts
  • Learn Exceptions
  • Web intro to Git
  • f-strings and */**
  • Explore some concepts possibly useful for interviews
    • Dynamic programming
    • Threads
    • Networking

3 of 41

Git Setup

4 of 41

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.

  • Installation is about as bad as Python- so be prepared

We’ll wait until next week for git commands.

5 of 41

Git Install for Windows

https://git-scm.com/downloads

6 of 41

Reviewing our Python

Table of Contents

- Dictionaries

  • Sets
  • Static methods

7 of 41

Intro to Dictionaries

>>> cnc = {}

>>> cnc["Key"] = "Value"

>>> cnc

{'Key': 'Value'}

>>> cnc["Key"]

'Value'

8 of 41

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'}

9 of 41

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!

10 of 41

Exceptions

How to fail well.

Table of Contents

- Basic exceptions

  • Else and finally
  • Raising exceptions
  • Custom exceptions

11 of 41

Basic Exception

try:

print(“a”)

1 / 0

print(“b”)

except:

print(“error!”)�>>> a�>>> error!

Looks like “break” or “return”.

12 of 41

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).

13 of 41

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.

14 of 41

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

15 of 41

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.

16 of 41

Raising Exceptions

try:

raise ValueError()

except ValueError:

print(“a”)

else:

print(“success!”)

>>> a

We can also do this manually.

17 of 41

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)

18 of 41

Web Intro to Git

Guide recycled from previous project. Exact links and paths will not match.

19 of 41

Step 1 - Go to Repo

For this week it’s

https://github.com/KevinBacabac/WarGame

20 of 41

Step 2 - Click Fork

21 of 41

Step 3 - Go to the bots folder (files should be visible)

22 of 41

Step 4 - Click “Create new file” and paste your source code (or edit)

23 of 41

Step 5 - Save your changes; a commit appears

24 of 41

Step 6 - Click pull request then “Create pull request”

25 of 41

Step 7 - Optional comment and then submit

26 of 41

Bonus Material

(Co-op prep/ Advanced CS)

Table of Contents

- Algorithms

- Multithreaded code

- Databases

- Networking

27 of 41

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.

28 of 41

CS 341 - Algorithms in 3 minutes

Multiple strategies you can try

Divide and conquer

  • Split problem into smaller pieces (think binary search)

Greedy algorithms

  • E.g. Coin changing, pick the largest denomination first

Dynamic programming

  • Recursion but bottom-up rather than top-down
  • e.g. Fibonacci sequence with for loop

29 of 41

CS 341 - Recursion

Recursive

Fib(n)

If n < 2

Return 0

Return Fib(n - 1) + Fib(n - 2)

Runtime? Exponential.

30 of 41

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!

31 of 41

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

32 of 41

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)

33 of 41

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

34 of 41

CS 348 - Databases

A database stores tables. (Like a folder)

A table is like a spreadsheet with a specific format.

Columns

Rows / Records

35 of 41

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)

36 of 41

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.

37 of 41

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.

38 of 41

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.

39 of 41

So you don’t forget

40 of 41

Next Time

  • Variable scope
  • F-strings
  • * and ** arguments in functions
  • “is” keyword
  • Git by command line

There will be no lesson next week :(

What do you want to learn next?

41 of 41