Professional Documents
Culture Documents
Ex 2
Ex 2
To use undo operation in a Microsoft Word, the machine needs to remember the list of
states and operations made. To implement this in real time write a detailed program
with set of insertion and deletion operation functions.
Algorithm:
1. Initialize TextEditor:
• Initialize a TextEditor object with an empty initial text and an empty history
list.
2. Insert Text Operation:
• Define an insert_text method in the TextEditor class.
• Accept the text to be inserted (inserted_text) as a parameter.
• Create a tuple representing the operation (("insert", current_text,
inserted_text)).
• Append the tuple to the history list.
• Update the current text by concatenating it with the inserted text.
3. Delete Text Operation:
• Define a delete_text method in the TextEditor class.
• Accept the number of characters to delete (num_chars) as a parameter.
• Extract the deleted text from the end of the current text.
• Create a tuple representing the operation (("delete", current_text,
deleted_text)).
• Append the tuple to the history list.
• Update the current text by removing the last num_chars characters.
4. Undo Operation:
• Define an undo method in the TextEditor class.
• Check if the history list is not empty.
• Pop the last tuple from the history list.
• Extract the operation type, the current text, and the affected text.
• Based on the operation type:
• If it was an "insert" operation, update the current text to the previous
state.
• If it was a "delete" operation, update the current text to the previous
state by adding the affected text back.
5. Display Text:
• Define a display_text method in the TextEditor class.
• Print the current text.
6. Example Usage:
• Create a TextEditor object.
• Use the insert_text and delete_text methods to perform operations.
• Use the undo method to revert the last operation.
• Use the display_text method to show the current text.
Program:
class TextEditor:
def __init__(self):
self.text = ""
self.history = []
def undo(self):
if not self.history:
print("Nothing to undo.")
return
def display_text(self):
print("Current Text:", self.text)
# Example Usage:
editor = TextEditor()
editor.insert_text("Welcome to ")
editor.display_text()
editor.insert_text("python programming")
editor.display_text()
editor.delete_text(11)
editor.display_text()
editor.undo()
editor.display_text()
Output:
Current Text: Welcome to