目录
最近老看到一些比较奇怪的题目,继续给大家分享。
题目
模拟vim左右、replace的操作,大概意思如动图
l: move the cursor right
l: move the cursor right
h: move the cursor left
rx: replace the character under the cursor with x

解答
这道题其实不是特别麻烦,更像一道OOP设计题。网上也没看到类似的答案,自己写了个。
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())
微信扫一扫
支付宝扫一扫