Simple Text Editor

  • + 0 comments
    S, history = [], []
    Q = int(input())    # no. of operations
    for i in range(Q):
        op = input().split()
        
        if op[0] == "1":    # append()
            chars = op[1]
            S.extend(chars)
            history.append(("1", chars))
            
        elif op[0] == "2":  # delete()
            k = int(op[1])
            deleted = "".join(S[-k: ])
            history.append(("2", deleted))
            S = S[: -k]
            
        elif op[0] == "3":  # print()
            k = int(op[1]) - 1
            print(S[k])
            
        else:   # undo() either "1" or "2":
            last_op, chars = history.pop()
            if last_op == "1":
                S = S[: -len(chars)]
            elif last_op == "2":
                S.extend(chars)