Advertisement
CVSoft

(python2)oh god why

Dec 9th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. import re
  2.  
  3. re_MARKER = re.compile("\(([0-9]+)x([0-9]+)\)(.+)")
  4.  
  5. class CompressedString(object):
  6.     def __init__(self, s):
  7.         self.s = s
  8.  
  9.     def __len__(self):
  10.         return len(self.decompress())
  11.  
  12.     def __str__(self):
  13.         return self.decompress()
  14.  
  15.     def __repr__(self):
  16.         return self.s
  17.  
  18.     def decompress(self):
  19.         out = ""
  20.         s = self.s
  21.         while True:
  22.             m = re_MARKER.search(s)
  23.             if not m:
  24.                 out += s
  25.                 break #append the rest of s
  26.             out += self.s[:m.start()]
  27.             d = decompress(s[m.start():])
  28.             out += d[0]
  29.             s = d[1]
  30.         return out
  31.  
  32.  
  33. def decompress(s):
  34.     """please start with a (NxM) group"""
  35.     m = re_MARKER.match(s)
  36.     if not m: raise ValueError
  37.     m = m.groups()
  38.     if int(m[0]) > len(m[2]): raise IndexError
  39.     return (m[2][:int(m[0])]*int(m[1]), m[2][int(m[0]):])
  40.  
  41.  
  42. debug_total = 0
  43.  
  44. def super_decompress(s):
  45.     global debug_total
  46.     m = re_MARKER.search(s)
  47.     if not m: return len(s)
  48.     l = m.start()
  49.     m = m.groups()
  50.     p1 = s[l:]
  51.     unparsed = ''
  52.     while True:
  53.         if re_MARKER.match(p1):
  54.             p = decompress(p1)
  55.             p1 = p[0]
  56.             unparsed = p[1] + unparsed
  57.         else:
  58.             debug_total += len(p1)
  59.             l += len(p1)
  60.             p1 = unparsed
  61.             unparsed = ''
  62.             if not re_MARKER.match(p1):
  63.                 if p1:
  64.                     l += super_decompress(p1)
  65.                 break
  66.     return l
  67.  
  68. def main():
  69.     global debug_total
  70.     with open("input.txt", 'r') as f:
  71.         l = f.readline().strip("\r\n")
  72.         print "Part 1 solution:", len(CompressedString(l))
  73.         try:
  74.             print "Part 2 solution:", super_decompress(l)
  75.         except KeyboardInterrupt:
  76.             print debug_total
  77.  
  78. if __name__ == "__main__": main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement