Skip to content

Instantly share code, notes, and snippets.

@cgearhart
cgearhart / resampler.py
Created July 3, 2018 21:49
Resampling wheel (weighted random sampling) in python
def sample(weights, size=1):
beta = 0
samples = []
w_max = max(weights)
index = random.randint(1, N)
while len(samples) < size:
beta += random.uniform(0, 2 * w_max)
while w[index] < beta:
beta -= weights[index]
index += 1
@cgearhart
cgearhart / MST
Created March 31, 2014 16:54
Prim's Algorithm - Find MST of an undirected, arbitrarily connected graph
def mst(graph):
'''
mst retuns the minimum spanning tree of `graph`, which must be a symmetric NxN array, where
element (i,j) is the weight of the connection from node i to node j. The diagonal should be all
zeros (because i and j are the same point), and unconnected nodes are `None`.
The nth position of the array returned contains the parent node of node n. The order always
starts from node 0 as the root of the tree, so order[0] is always None.
'''
order = [None] * len(graph)