Here is a link back to the course syllabus/policy page.
This schedule is will be changing very frequently, please check it at least every class day, and before starting work on any assignment (in case the content of the assignment has changed).
When there is a reading assignment, please read the named section(s) before that day.
If you see the symbol below, it means that class was videoed and you can get a link by e-mailing me. Note that if you know ahead of time that you will miss a class, you should tell me and I will be sure to video that day for you.
Recall from the syallabus that these are short emails you should send to your instructor about the current readings you've been assigned and/or the material we've been discussing in class.With that understood, please do the following T&Qs (send each in its own email to your instructor) before class on Monday (Tuesday is also OK, if this seems like too much, too soon, or if you have a question you want to ask in class about T&Qs on Monday):
Their content should be a thought or question you might have about the topic in question, expressed in just a few sentences (or even one, very well crafted sentence!).
There is no requirement about depth or sophistication of your T&Qs, other than that they show real engagement with the material. For example, something like"I think American politics suck."does not show engagement [about a reading on current events], while"This article says that the Electoral College has its roots in the racist origins of the US Consstitution, and while I can see that is important, I don't see any path to changing the way we elect presidents in the near future."does.
Also, don't be embarrassed if your T&Q is a question and not a statement. If there is something in the assigned T&Q topic which you don't understand, state clearly and explicitly what that confusing bit is. E.g.,"This article talks about the problem with the Electoral College being that one person does not have one vote, but I don't understand the reasoning there, or the example of big states and small ones — don't big states have more Electoral College votes, so what's the problem with that?"would be fine [on the same current event topic].
Each T&Q is graded 0 or 1 ... you should expect to get pretty much all 1s on your T&Qs, so long as you are actually engaging with the readings and class material, and keeping on schedule with them.
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,20,1000) y1 = np.sin(x) y2 = np.cos(x) plt.plot(x, y1, '-b', label='sine') plt.plot(x, y2, '-r', label='cosine') plt.legend(loc='upper left') plt.show()
import random def guess(n=1023): if n < 1: print("Input must be a natural number") return number = random.randint(0,n) guesses = 0 while True: guess_text = input("Guess the number from 0 to %d: " % n) if guess_text == "I give up": print("Give up, eh? Well, my number was %d." % number) return guess = int(guess_text) if guess < 0 or guess > n: print("Your guesses must be integers in the range from 0 to %d." % n) continue guesses += 1 if guess > number: print("Too high") elif guess < number: print("Too low") else: print("Got it (in %d guesses)!!" % guesses) returnTry running this to play the game — come up with a good strategy!
class Quizzer: def __init__(self, max_val): import random self.n = random.randint(0,max_val) self.max_val = max_val def try_guess(self, k): if k < 0 or k >self.max_val: return 17 if k < self.n: return -1 elif k > self.n: return 1 else: return 0 def __str__(self): return str(self.n)For example, it can be used as in the following
q=new Quizzer(65635) for i in range(65535): ans=q.try_guess(i) if ans == -1: print("Too low, trying again") elif ans == +1: print("Too high, how did that happen?") elif ans == 0: print("Got it! Answer was %d" % i) break else: print("weird. quitting") breakwhich implements the naïve searching algorithm.
class BSTnode: def __init__(self,data,left=None,right=None): self.data = data self.left = left self.right = right def is_leaf(self): return self.left==None and self.right==NoneThis code includes the possibly convenient method that tells if a node is a leaf, is_leaf().
class BSTnode: def __init__(self,data,parent=None,left=None,right=None): self.data = data self.parent = parent self.left = left self.right = right def is_leaf(self): return self.left==None and self.right==None def is_root(self): return self.parent==NoneThis version of the code includes the possibly convenient method that tells if a node is the root of the tree, is_root().
def print_letter_counts(string): counts = {} for i in string: if i in counts: counts[i] += 1 else: counts[i] = 1 for i in counts: print("Letter "+i+" ocurred with frequency "+str(counts[i]))
def print_letter_counts_array(string): import numpy as np counts = np.zeros(26, np.int) for i in string: counts[ord(i)-ord('a')] += 1 for i in range(26): print("Letter "+chr(i+ord('a'))+" ocurred with frequency "+str(counts[i]))
raise IndexError("Key not found in this hash table")
with open('filename','r') as f: for line in f: print(line) # or do anything you want to do with that line
def __iadd__(self, item): if type(item) == str: self.add_vertex(item) elif type(item) == tuple: self.add_edge(item) else raise ValueError("Can only add a vertex [=str] or edge =[tuple].")[To do the same thing for graphs rather than digraphs, replace every occurrance of "tuple" in that code with "set".]
import matplotlib.pyplot as plt import math def dots_around_the_circle(n, self_loop_locs): # n here is the number of dots; # self_loop_locs is a list of # the indices of the self-loops x = [] # will be the x-coords of the vertices y = [] # will be the x-coords of the vertices label_x = [] # will be the x-coords of the labels label_y = [] # will be the y-coords of the labels labels="ABCDEFGHIJKLMNOPQRSTUVWXYZ" # will be the label values; not a # good way to do this! will not work # if more than 26 vertices; use # the real labels in your code for i in range(n): x.append(math.cos(2*i*math.pi/n)) label_x.append(1.2*math.cos(2*i*math.pi/n)) y.append(math.sin(2*i*math.pi/n)) label_y.append(1.2*math.sin(2*i*math.pi/n)) ax = plt.gca() ax.set_xlim((-1.5,1.5)) ax.set_ylim((-1.5,1.5)) ax.set_aspect('equal') # set aspect ratio, so circle will be round not oval plt.scatter(x,y,s=200) # plot the vertices for i in range(n): ax.annotate(labels[i],[label_x[i],label_y[i]]) # add the labels if i in self_loop_locs: # this will # plot the selected self-loops edges loop = plt.Circle([1.2*x[i],1.2*y[i]], .2, color='b', fill=False) ax.add_artist(loop) plt.show()Try running dots_around_the_circle(6,[1,3,4]), for example.
x == 2*x 1234567890 < x x == x + 1 -x < -123123123123This can make for much cleaner code than using, say, None as an estimated distance value when none is yet known.
class Graph: ... def add_vertex(... ... @staticmethod def rand_adj_mat(... ...Then you would use this with something like
gr = Graph() ... stuff with gr, such as ,,, gr.add_vertex("A") ... ... now to make an adjacency matrix m = Graph.rand_adj_mat(5, .4) ... note that was called with Graph and not gr ... you could even have done that before gr was defined: ... no specific instance of Graph need exist before ... using rand_adj_mat, since it is a staticmethod
def greedy_euler(self, v): path = [] while True: successful = False for e in self.edges: if v in e: if e in path: continue if len(e) == 1: w = v else: list_version = list(e) for a in list_version: if a != v: w = a break path.append(e) v = w successful = True if not successful: break if len(path) != len(self.edges): return ("Failed",path) return path
>>> from graph import * >>> m=Graph.rand_adj_mat(5,.5) >>> m array([[0, 1, 0, 1, 0], [1, 0, 1, 0, 0], [0, 1, 1, 0, 1], [1, 0, 0, 0, 1], [0, 0, 1, 1, 1]]) >>> g=Graph() >>> g.set_adjacency(m) >>> g.display([{"A","D"},{"D","E"},{"E"},{"E","C"}])would make the image
ax = plt.gca() ax.set_xlim((-1.6,1.6)) plt.setp(ax.get_xticklabels(), visible=False) ax.xaxis.set_tick_params(size=0) ax.set_ylim((-1.6,1.6)) plt.setp(ax.get_yticklabels(), visible=False) ax.yaxis.set_tick_params(size=0) ax.set_aspect('equal')to set up the axes without tick marks or numbers [because they are irrelevant to the graph information] and the aspect ratio
clean_string = "" for c in input_string.lower(): if c.isalpha(): clean_string += cThis may be useful in implementing cryptosystems in Python.
k=b'asdfjkl;asdfjkl;asdfjkl;asdfjkl;' obj=AES.new(k, AES.MODE_ECB) ciphertext=obj.ecrypt(plaintext)Yes, please use that stupid key b'asdfjkl;asdfjkl;asdfjkl;asdfjkl;' when you encrypt — that way, your instructor will be able to decrypt the message.
from math import gcd if gcd(a,b) == 1: print("They're relatively prime.") else: print("They are NOT relatively prime.")since having a non-trivial common factor means their greatest common factor is not just 1.
Jonathan Poritz (jonathan@poritz.net) | Last modified: |
Everything on
Jonathan Poritz's web pages is by Jonathan A. Poritz and is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License unless otherwise specified. |