Algorithm Problem Sharing: VimOperator – Simple operation simulation of Vim

Table of Contents

最近老看到一些比较奇怪的题目,继续给大家分享。

题目

模拟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

算法题分享:VimOperator - Vim的简单操作模拟 - giphy - Jake blog

解答

这道题其实不是特别麻烦,更像一道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())

 

 

This site Original article All followed" Attribution—NonCommercial—ShareAlike 4.0 (CC BY-NC-SA 4.0) ”。 Please keep the following marks for sharing and interpretation:

Original author: Jake Tao Source: 「算法题分享:VimOperator – Vim的简单操作模拟」

Praise 860
0 0 860

Further reading

Post a reply

Log in can only be commented on later
Share this page
Back to top