Skip to content

Instantly share code, notes, and snippets.

View alexgolec's full-sized avatar

Alex Golec alexgolec

View GitHub Profile
import argparse
import collections
import datetime
import openpyxl
import tableformatter
import re
import tda
def convert(conversions, start, end):
'Given a conversion structure, performs a constant-time conversion'
try:
start_root, start_rate = conversions[start]
end_root, end_rate = conversions[end]
except KeyError:
return None
if start_root != end_root:
return None
from collections import deque
def make_conversions(graph):
def conversions_bfs(rate_graph, start, conversions):
to_visit = deque()
to_visit.appendleft( (start, 1.0) )
while to_visit:
node, rate_from_origin = to_visit.pop()
conversions[node] = (start, rate_from_origin)
def add_conversion(self, orig, dest, rate):
'Insert a conversion into the graph. Note we insert its inverse also.'
if orig not in self.graph:
self.graph[orig] = {}
self.graph[orig][dest] = rate
if dest not in self.graph:
self.graph[dest] = {}
self.graph[dest][orig] = 1.0 / rate
@alexgolec
alexgolec / bfs.py
Last active September 4, 2019 13:37
from collections import deque
def bfs(rate_graph, start, end):
to_visit = deque()
to_visit.appendleft( (start, 1.0) )
visited = set()
while to_visit:
node, rate_from_origin = to_visit.pop()
if node == end:
from collections import deque
def __dfs_helper(rate_graph, node, end, rate_from_origin, visited):
if node == end:
return rate_from_origin
visited.add(node)
for unit, rate in rate_graph.get_neighbors(node):
if unit not in visited:
class RateGraph(object):
def __init__(self, rates):
'Initialize the graph from an iterable of (start, end, rate) tuples.'
self.graph = {}
for orig, dest, rate in rates:
self.add_conversion(orig, dest, rate)
def add_conversion(self, orig, dest, rate):
'Insert a conversion into the graph.'
class DisjointSet(object):
def __init__(self):
self.parents = {}
def get_root(self, w):
words_traversed = []
while self.parents[w] != w:
words_traversed.append(w)
w = self.parents[w]
for word in words_traversed:
synonyms = defaultdict(set)
for w1, w2 in synonym_words:
for w in synonyms[w1]:
synonyms[w].add(w2)
synonyms[w1].add(w2)
for w in synonyms[w2]:
synonyms[w].add(w1)
synonyms[w2].add(w1)
def synonym_queries(synonym_words, queries):
'''
synonym_words: iterable of pairs of strings representing synonymous words
queries: iterable of pairs of strings representing queries to be tested for
synonymous-ness
'''
synonyms = defaultdict(set)
for w1, w2 in synonym_words:
synonyms[w1].add(w2)