We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classEditor:def__init__(self):"""Initialize the text editor."""self.text=""self.history=[]defappend(self,word):"""Append a word to the end of the text."""self.history.append(self.text)self.text+=worddefdelete(self,k):"""Delete the last k characters from the text."""if0<=k<=len(self.text):self.history.append(self.text)self.text=self.text[:-k]else:raiseValueError("Cannot delete more characters than the length of the text.")defprint_char(self,k):"""Print the character at the specified index in the text."""if1<=k<=len(self.text):print(self.text[k-1])else:raiseIndexError("Index out of range.")defundo(self):"""Undo the last operation by restoring the previous state of the text."""ifself.history:self.text=self.history.pop()else:print("Nothing to undo.")# Test the Editor classeditor=Editor()count=int(input())for_inrange(count):operation=input().split()op_code=operation[0]try:ifop_code=='1':editor.append(operation[1])elifop_code=='2':editor.delete(int(operation[1]))elifop_code=='3':editor.print_char(int(operation[1]))elifop_code=='4':editor.undo()else:print("Invalid operation code.")except(ValueError,IndexError)ase:print(f"Error: {e}")
Cookie support is required to access HackerRank
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 →