Advertisement
Guest User

whatfuck.py

a guest
Dec 26th, 2012
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. class State:
  2.     def __init__(self,arr=[0],arr_i=0,code_i=0):
  3.         self.arr = arr
  4.         self.arr_i = arr_i
  5.         self.code_i = code_i
  6.     def copy(self):
  7.         return State(self.arr[:],self.arr_i,self.code_i)
  8.     def __str__(self):
  9.         a = '['+''.join(map(str,self.arr))+']'
  10.         p = ' '*(self.arr_i) + ' ^' + ' '*(len(self.arr) - self.arr_i + self.code_i) + ' ^'
  11.         return a + ' ' + code + '\n' + p
  12.     def __repr__(self):
  13.         return 'State('+`self.arr`+','+`self.arr_i`+','+`self.code_i`
  14.        
  15. #instructions
  16. #Return a new state if one is created, otherwise return None
  17. def while_open(state):
  18.     if state.arr[state.arr_i]:
  19.         state.code_i += 1
  20.     else:
  21.         state.code_i = brackets[state.code_i]+1
  22.        
  23. def while_close(state):
  24.     state.code_i = brackets[state.code_i]
  25.    
  26. def flip(state):
  27.     state.arr[state.arr_i] = 1 - state.arr[state.arr_i]
  28.     state.code_i += 1
  29.    
  30. def right(state):
  31.     state.arr_i += 1
  32.     if state.arr_i >= len(state.arr):
  33.         state.arr.append(0)
  34.     state.code_i += 1
  35.    
  36. def left(state):
  37.     if state.arr_i:
  38.         state.arr_i -= 1
  39.     else:
  40.         state.arr.insert(0,0)
  41.     state.code_i += 1
  42.    
  43. def nd_choose(state):
  44.     state.code_i += 1
  45.     c = state.copy()
  46.     state.arr[state.arr_i] = 0
  47.     c.arr[c.arr_i] = 1
  48.     return c
  49.    
  50. instructions = {
  51.     '[':while_open,
  52.     ']':while_close,
  53.     '*':flip,
  54.     '>':right,
  55.     '<':left,
  56.     '?':nd_choose }
  57.  
  58. states = [State()]
  59. code = raw_input()
  60.  
  61. #Find matching brackets
  62. brackets = [0]*len(code)
  63. stack = []
  64. for i in range(len(code)):
  65.     if code[i]=='[':
  66.         stack.append(i)
  67.     elif code[i]==']':
  68.         b = stack.pop()
  69.         brackets[i]=b
  70.         brackets[b]=i
  71.        
  72. while states:
  73.     new_states = []
  74.     for s in states:
  75.         c = code[s.code_i]
  76.         n = instructions[c](s)
  77.         if n:
  78.             new_states.append(n)
  79.     states.extend(new_states)
  80.     terminated = filter(lambda s:s.code_i == len(code),states)
  81.     if any(map(lambda s:s.arr[s.arr_i],terminated)):
  82.         print 1
  83.         break
  84.     states = filter(lambda s:s.code_i < len(code),states)
  85.     if len(states) == 0:
  86.         print 0
  87.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement