Skip to content

Instantly share code, notes, and snippets.

@nolanlum
Created October 11, 2013 01:37
Show Gist options
  • Select an option

  • Save nolanlum/6928366 to your computer and use it in GitHub Desktop.

Select an option

Save nolanlum/6928366 to your computer and use it in GitHub Desktop.
import urllib2
import re
import json
from collections import namedtuple
oper_pattern = re.compile(r"(abs|add|subtract|multiply)\(([-0-9]+)(?:,([-0-9]+))?\)")
oper_map = {
"abs" : lambda x, y: abs(long(x)),
"add" : lambda x, y: long(x) + long(y),
"subtract" : lambda x, y: long(x) - long(y),
"multiply" : lambda x, y: long(x) * long(y)
}
url_base = "http://www.crunchyroll.com/tech-challenge/roaming-math/[email protected]/"
Node = namedtuple('Node', ['previous', 'distance', 'visited'])
def fetch_url(id):
try:
page = urllib2.urlopen(url_base + str(id))
children = []
for x in map(str.strip, page):
if x == 'DEADEND' or x == 'GOAL':
return x
children.append(eval_expr(x))
return map(long, children)
except:
print "**ERROR 404: " + id
def eval_expr(expr):
m = oper_pattern.search(expr)
if m is not None:
repl = oper_map[m.group(1)](m.group(2), m.group(3))
expr = expr.replace(m.group(0), str(repl))
return eval_expr(expr)
return expr
# BFS then DFS
def crawl(start):
node_count = 1
goal = -1
shortest_path = None
directed_cycle_count = 0
nodes_seen = {}
crawl_queue = [start]
# add source to seen list
nodes_seen[start] = Node(None, 0, False)
while len(crawl_queue) > 0:
cur = crawl_queue.pop(0)
children = fetch_url(cur)
print "%s: %s" % (cur, children)
if children == 'GOAL':
goal = cur
shortest_path = []
while cur in nodes_seen:
shortest_path.insert(0, cur)
cur = nodes_seen[cur].previous
elif children == 'DEADEND':
continue
else:
cur_distance = nodes_seen[cur].distance
for x in children:
if x not in nodes_seen:
nodes_seen[x] = Node(cur, cur_distance + 1, False)
node_count += 1
if x not in crawl_queue:
crawl_queue.append(x)
if x in nodes_seen and nodes_seen[x].visited:
directed_cycle_count += 1
nodes_seen[cur] = nodes_seen[cur]._replace(visited=True)
print json.dumps({
'goal': goal,
'node_count' : len(nodes_seen),
'shortest_path' : shortest_path,
'directed_cycle_count' : directed_cycle_count
})
crawl(587474L)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment