You are viewing a single comment's thread. Return to all comments →
import sys class TextEditor(): def __init__(self): self.text = "" self.op_stack = [] def append(self, s, undo=False): if not undo: self.op_stack.append((1, s)) self.text += s def delete(self, k, undo=False): if not undo: self.op_stack.append((2, self.text[-k:])) self.text = self.text[:-k] def _print(self, k): print(self.text[k-1]) def undo(self): if self.op_stack: op_type, s = self.op_stack.pop() match op_type: case 1: self.delete(len(s), undo=True) case 2: self.append(s, undo=True) case _: print('Cannot Undo Command!', file=sys.stderr) exit(1) if __name__ == "__main__": q = int(input()) editor = TextEditor() for _ in range(q): op = input() match int(op[0]): case 1: editor.append(op.split()[1]) case 2: editor.delete(int(op.split()[1])) case 3: editor._print(int(op.split()[1])) case 4: editor.undo() case _: print('Unknown Command!', file=sys.stderr) exit(1)
Seems like cookies are disabled on this browser, please enable them to open this website
Simple Text Editor
You are viewing a single comment's thread. Return to all comments →