The task is to build to a text manipulator: A program that simulates a set of text manipulation commands.Given an input piece of text and a string of commands, output the mutated input text and cursor position.
Starting simple:
Commands
h: move cursor one character to the left
l: move cursor one character to the right
r<c>: replace character under cursor with <c>
Repeating commands
# All commands can be repeated N times by prefixing them with a number.
#
# [N]h: move cursor N characters to the left
# [N]l: move cursor N characters to the right
# [N]r<c>: replace N characters, starting from the cursor, with <c> and move the cursor
Examples
# We'll use Hello World as our input text for all cases:
#
# Input: hhlhllhlhhll
# Output: Hello World
# _
# 2
#
# Input: rhllllllrw
# Output: hello world
# _
# 6
#
# Input: rh6l9l4hrw
# Output: hello world
# _
# 6
#
# Input: 9lrL7h2rL
# Output: HeLLo WorLd
# _
# 3
#
# Input: 999999999999999999999999999lr0
# Output: Hello Worl0
# _
# 10
#
# Input: 999rsom
# Output: sssssssssss
# _
# 10
I have written the following piece of code, but getting an error:
class Editor():
def __init__(self, text):
self.text = text
self.pos = 0
def f(self, step):
self.pos += int(step)
def b(self, step):
self.pos -= int(step)
def r(self, char):
s = list(self.text)
s[self.pos] = char
self.text = ''.join(s)
def run(self, command):
command = list(command)
# if command not in ('F','B', 'R'):
#
while command:
operation = command.pop(0).lower()
if operation not in ('f','b','r'):
raise ValueError('command not recognized.')
method = getattr(self, operation)
arg = command.pop(0)
method(arg)
def __str__(self):
return self.text
# Normal run
text = 'abcdefghijklmn'
command = 'F2B1F5Rw'
ed = Editor(text)
ed.run(command)
print(ed)
I have used 'F' and 'B' in my code instead of 'h' and 'l', but the problem is I am missing a piece that allows me to define the optional 'N'. My code only works if there is a number defined after an operation. How can I fix the code above to meet all the requirements?
from Text Manipulator: String position movement
No comments:
Post a Comment