Advertisement
Guest User

ite.py

a guest
Jan 9th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. def ite_interpretter(prog,inp):
  4.     state = {'0':0, '1':1}
  5.     for i,char in enumerate(inp):
  6.         if char!='0' and char!='1':
  7.             raise Exception("Invalid input character '%s'"%char)
  8.         state['I%d'%i] = int(char)
  9.     output = 0 # default value for empty programs
  10.     output_num = 0
  11.     line_num = 0
  12.     for line in prog.splitlines():
  13.         line_num += 1
  14.         # allow comments and blank lines
  15.         if line=="" or line[0]=="#":
  16.             continue
  17.         terms = line.rstrip().split(' ')
  18.         try:
  19.             # optionally allow custom names
  20.             if len(terms) == 3:
  21.                 name=None
  22.             elif len(terms) == 4:
  23.                 name=terms[0]
  24.                 del terms[0]
  25.                 if len(name)<2 or name[-1]!=":" or (name[0] in ['Q','I']):
  26.                     raise Exception("invalid custom name specifier")
  27.                 name=name[:-1]
  28.             else:
  29.                 raise Exception("invalid number of terms")
  30.             terms = [state[x] for x in terms]
  31.         except Exception as e:
  32.             raise Exception("Error parsing line %d: %r, %s"%(line_num,line,e))
  33.         output = terms[1] if terms[0] else terms[2]
  34.         if name:
  35.             state[name] = output
  36.         state['Q%d'%output_num] = output
  37.         output_num += 1
  38.     return output
  39.  
  40. if __name__ == "__main__":
  41.     import sys
  42.     if len(sys.argv)<3:
  43.         print "Usage: python ite.py <prog> <input>"
  44.         sys.exit(1)
  45.  
  46.     prog=open(sys.argv[1]).read()
  47.     inp=sys.argv[2]
  48.  
  49.     print ite_interpretter(prog,inp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement