#!/usr/bin/env python #Author: Shriphani Palakodety #Mail: spalakod@purdue.edu #Alternate Mail: shriphani@shriphani.com #Blog: http://shriphani.com/blog class Cell: '''Class describing the cell of a tape''' def __init__(self, mark=0): '''Each cell is unmarked by default''' self.mark = mark def setMark(self): self.mark = 1 def remMark(self): self.mark = 0 class Tape: '''Class describing the infinite reel in the machine''' def __init__(self): '''Each tape has an infinite number of cells both ways''' self.reel = [] for i in xrange(5): #we display only the required elements at a time cell = Cell() self.reel.append(cell) def __str__(self): printstr = "....." for cell in self.reel: printstr += str(cell.mark)+"," printstr += "....." return printstr class Head: '''Class describing the head''' def __init__(self, tape, position=0): self.position = position self.tape = tape def moveLeft(self): if self.position != 0: self.position -= 1 else: extension = [] extension.append(Cell()) self.tape = extension + tape.reel def etchMark(self): self.tape.reel[self.position].setMark() def remMark(self): self.tape.reel[self.position].remMark() def moveRight(self): if self.position == len(self.tape.reel) - 1: self.tape.reel.append(Cell()) self.position += 1 def getPosition(self): return self.position class Machine: '''Class describing the Post Machine''' def __init__(self, tape): self.tape = tape self.head = Head(tape) self.commands = {} def parseInstruction(self, number, action, jump): '''Instruction is of form "[number, action, jump]"''' self.commands[number] = [action, jump] def beginExecution(self): instruction = 0 action = self.commands[instruction][0] while action != "exit": if action == "<": self.head.moveLeft() elif action == ">": self.head.moveRight() elif action == "mark": self.head.etchMark() elif action == "unmark": self.head.remMark() print self instruction = self.commands[instruction][1] action = self.commands[instruction][0] return def __str__(self): '''This returns tape with the head displayed''' a = str(self.tape) posn = self.head.getPosition() temp = "....." for i in xrange(len(self.tape.reel)): if i == posn: temp += "["+str(self.tape.reel[i].mark)+"], " else: temp += str(self.tape.reel[i].mark) + ", " temp += "....." return temp tape = Tape() a = Machine(tape) print "Initial Stage" print a def run(input_file): infile = open(input_file, 'r') b = infile.readlines() for instruction in b: try: splits = instruction.split(",") number = int(splits[0].strip()) action = splits[1].strip() if action == "exit": a.parseInstruction(number, action, 0) else: jump = int(splits[2].strip()) a.parseInstruction(number, action, jump) except KeyError: return infile.close() a.beginExecution() filename = raw_input("File: ") run(filename)