Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- def ite_interpretter(prog,inp):
- state = {'0':0, '1':1}
- for i,char in enumerate(inp):
- if char!='0' and char!='1':
- raise Exception("Invalid input character '%s'"%char)
- state['I%d'%i] = int(char)
- output = 0 # default value for empty programs
- output_num = 0
- line_num = 0
- for line in prog.splitlines():
- line_num += 1
- # allow comments and blank lines
- if line=="" or line[0]=="#":
- continue
- terms = line.rstrip().split(' ')
- try:
- # optionally allow custom names
- if len(terms) == 3:
- name=None
- elif len(terms) == 4:
- name=terms[0]
- del terms[0]
- if len(name)<2 or name[-1]!=":" or (name[0] in ['Q','I']):
- raise Exception("invalid custom name specifier")
- name=name[:-1]
- else:
- raise Exception("invalid number of terms")
- terms = [state[x] for x in terms]
- except Exception as e:
- raise Exception("Error parsing line %d: %r, %s"%(line_num,line,e))
- output = terms[1] if terms[0] else terms[2]
- if name:
- state[name] = output
- state['Q%d'%output_num] = output
- output_num += 1
- return output
- if __name__ == "__main__":
- import sys
- if len(sys.argv)<3:
- print "Usage: python ite.py <prog> <input>"
- sys.exit(1)
- prog=open(sys.argv[1]).read()
- inp=sys.argv[2]
- print ite_interpretter(prog,inp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement