Monday, December 27, 2010

Reference point

Learning Python. No doubt, this code will become a source of embarrassment in the future.

(Actually, I'm embarrassed already...)

CoderLoop: reversesequence
#!/usr/bin/python

import sys
from collections import defaultdict

f = open(sys.argv[1], 'r')

succ = defaultdict(set)

for [p, q] in [line.split() for line in f]:
   succ[p].add(q)
   succ[None].add(p)
   succ[None].add(q)

stack = [None]
visited = set([None])

while stack:
   p = stack[-1]
   nexts = [q for q in succ[p] if q not in visited]

   if nexts:
      stack.extend(nexts)
   else:
      if p not in visited: print p
      visited.add(p)
      stack.pop()

Dear god...

CoderLoop: reversewords
#!/usr/bin/python

import sys
import re

print re.sub(r"\w+", lambda m: m.group(0)[::-1], open(sys.argv[1], 'r').read()),