Skip to content

Instantly share code, notes, and snippets.

@zpconn
zpconn / tree_pairs.py
Created January 13, 2014 04:26
Given a list of pairs, each containing the name of a node and the name of its parent, respectively, this builds the full tree as a nested dictionary. Note that the parent of the root node is specified by None.
def build(pairs, root=None):
tree = {}
for (child, parent) in pairs:
if parent == root:
tree[child] = build(filter(lambda x: x != (child, parent), pairs), child)
return tree
print build([("H", "G"), ("F", "G"), ("G", "D"), ("E", "D"), ("A", "E"), ("B", "C"), ("C", "E"), ("D", None)])
@zpconn
zpconn / expr.py
Created January 13, 2014 04:23
Very simple shunting-yard parser for converting in-fix to post-fix.
def postfix(tokens):
output_stack = []
op_stack = []
for token in tokens:
if is_number(token):
output_stack.append(token)
elif token in ['+', '-', '*', '/']:
while len(op_stack) > 0:
if (token in ['+', '-'] and op_stack[-1] in ['*', '/']) or (token in ['*', '/'] and op_stack[-1] in ['*', '/']):
output_stack.append(op_stack.pop())
@zpconn
zpconn / scatter.py
Created December 2, 2013 21:03
Generates a scatter plot of lat/lon data on a map of the United States.
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Point, MultiPoint
import pandas as pd
import matplotlib.pyplot as plt
x = []
y = []
with open('data.tsv', 'r') as fp:
for line in fp:
s = line.split('\t')
@zpconn
zpconn / markov.py
Created November 16, 2013 05:46
A random text generator based on an N=2 Markov chain model.
from collections import defaultdict
import random
class Markov:
memory = defaultdict(list)
separator = ' '
def get_initial(self):
return (' ', ' ')
@zpconn
zpconn / pid.py
Created November 14, 2013 20:00
A simple discrete-time PID controller.
# A simple discrete-time PID controller. If plot is true, this will use matplotlib to show a graph.
# Otherwise, it will simply print out the successive values of the controller.
plot = True
if __name__ == '__main__':
if plot:
import matplotlib.pyplot as plt
v = [0] * 100
@zpconn
zpconn / cluster.py
Last active December 24, 2015 22:09
Naive clustering based on gaps between successive numbers. Must have lists.csv in the same directory as cluster.py. lists.csv should contain several columns of real numbers with labels in the header row. This filters out zero values, which will obviously always be in the same cluster. Optional command line argument specifies a custom gap, which …
def pairify(it):
it0, it1 = itertools.tee(it, 2)
first = next(it0)
return zip(itertools.chain([first, first], it0), it1)
def cluster(sequence, maxgap):
batch = []
for prev, val in pairify(sequence):
if abs(val - prev) >= maxgap:
yield batch
@zpconn
zpconn / Hegex.hs
Last active December 17, 2015 03:49
This is a really short implementation of a pattern matcher for a restricted class of regular expressions, namely those consisting of character literals and the special symbols . ^ & * where . matches any single character, ^ binds the pattern to the target string's beginning, $ binds the pattern to the target's ending, and * matches zero or more …
module Main (main) where
match :: String -> String -> Bool
match ('^':rest) text = matchLocal rest text
match rex (c:rest) = matchLocal rex (c:rest) || match rex rest
match _ _ = False
matchLocal :: String -> String -> Bool
matchLocal [] _ = True
matchLocal "$" [] = True