Cursor in a Line of Text
Implement a class LineEditor that edits one line of text through a cursor. The cursor sits between characters: position 0 is before the first character and position len(line) is after the last one. Write these methods:
LineEditor()starts with an empty line and the cursor at0.insert_text(s)insertssat the cursor. The cursor ends up right after the inserted text. Returns the new cursor position.move_cursor(steps)moves the cursorstepspositions to the right, or to the left whenstepsis negative. The cursor stops at the start or the end of the line instead of going past it. Returns the new cursor position.delete_chars(k)deletes characters next to the cursor. Whenkis positive it deletes up tokcharacters to the right of the cursor, like the Delete key, and the cursor stays where it is. Whenkis negative it deletes up to-kcharacters to the left of the cursor, like Backspace, and the cursor moves left to where the deleted text began. If the line ends first, fewer characters are deleted. Returns the deleted text in its original left to right order, or""if nothing was deleted.get_line()returns the whole line.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
LineEditor()
insert_text("helo") returns 4
move_cursor(-1) returns 3
insert_text("l") returns 4
move_cursor(10) returns 5
delete_chars(-2) returns "lo"
get_line() returns "hel"
move_cursor(-9) returns 0
delete_chars(2) returns "he"
get_line() returns "l"
The l goes in before the o, making hello with the cursor at 4. Moving 10 right stops at the end, 5. Backspacing two deletes lo, and after jumping to the start, deleting two to the right removes he.
Constraints
sis1to5lowercase letters, and the line never grows past60characters.-10 <= steps <= 10-6 <= k <= 6andkis never0.- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.