Algorithm Problem Sharing: VimOperator – Simple Operation Simulation of Vim

Table of Contents

I've been seeing some rather strange questions lately, so I'll continue to share them with you.

topic

The animation simulates the left/right and replace operations in Vim, roughly as shown in the GIF.

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

answer

This question isn't particularly difficult; it's more like an OOP design problem. I didn't find a similar answer online, so I wrote one myself.

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 siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"Algorithm Problem Sharing: VimOperator – Simple Simulation of Vim Operations"

860
0 0 860

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top