# 算法题分享：VimOperator – Vim的简单操作模拟

## 题目

l: move the cursor right
l: move the cursor right
h: move the cursor left
rx: replace the character under the cursor with x

## 解答

```class VimOperator(object):
def __init__(self, _input, action):
self.input = list(_input)
self.action = action
self.index = 0
self.left_limit = 0
self.right_limit = len(self.input) - 1

def process(self):
idx = 0
while idx < len(self.action):
ch = self.action[idx]
#case 1: for number
if ch.isnumeric():
for _ in range(int(ch)):
self.move(self.input[idx + 1])
idx += 2
#case 2: for left / right
elif ch in ('l', 'h'):
self.move(ch)
idx += 1
#case 3: replace value
elif ch == 'r':
self.input[self.index] = self.action[idx + 1]
idx += 2

def move(self, direction):
if direction == 'h':
self.index = max(self.left_limit, self.index - 1)
else :
self.index = min(self.right_limit, self.index + 1)

def get_output(self):
return "".join(self.input)

s = VimOperator('hello', 'llhrx')
s.process()
print(s.get_output())```

[0人评了分，平均: 0/5]