Simple Text Editor

  • + 0 comments
    s = ''  # Current string state
    history = []  # Stack of undo operations (each is a function that reverts a change)
    
    for _ in range(int(input())):
        command = input().rstrip().split()
        
        match command[0]:
            case '1':  # Append operation
                # Save undo operation (removes the appended part)
                # Using lambda with default arg to capture current command[1] length
                history.append(lambda s, chars_to_remove=len(command[1]): s[:-chars_to_remove])
                # Perform the append
                s += command[1]
                
            case '2':  # Delete operation
                chars_to_delete = int(command[1])
                # Save undo operation (re-adds the deleted portion)
                # Store the deleted substring as default arg to avoid late binding issues
                history.append(lambda s, deleted_part=s[-chars_to_delete:]: s + deleted_part)
                # Perform the deletion
                s = s[:-chars_to_delete]
                
            case '3':  # Print character at index
                print(s[int(command[1]) - 1])
                
            case '4':  # Undo last operation
                if history:  # Only undo if there's history
                    # Apply the most recent undo operation
                    s = history.pop()(s)