Simple Text Editor

  • + 0 comments
    class Editor:
        def __init__(self):
            """Initialize the text editor."""
            self.text = ""
            self.history = []
    
        def append(self, word):
            """Append a word to the end of the text."""
            self.history.append(self.text)
            self.text += word
    
        def delete(self, k):
            """Delete the last k characters from the text."""
            if 0 <= k <= len(self.text):
                self.history.append(self.text)
                self.text = self.text[:-k]
            else:
                raise ValueError("Cannot delete more characters than the length of the text.")
    
        def print_char(self, k):
            """Print the character at the specified index in the text."""
            if 1 <= k <= len(self.text):
                print(self.text[k - 1])
            else:
                raise IndexError("Index out of range.")
    
        def undo(self):
            """Undo the last operation by restoring the previous state of the text."""
            if self.history:
                self.text = self.history.pop()
            else:
                print("Nothing to undo.")
    
    # Test the Editor class
    editor = Editor()
    count = int(input())
    for _ in range(count):
        operation = input().split()
        op_code = operation[0]
        try:
            if op_code == '1':
                editor.append(operation[1])
            elif op_code == '2':
                editor.delete(int(operation[1]))
            elif op_code == '3':
                editor.print_char(int(operation[1]))
            elif op_code == '4':
                editor.undo()
            else:
                print("Invalid operation code.")
        except (ValueError, IndexError) as e:
            print(f"Error: {e}")