使用 OOP 解决此问题的最佳方法是什么?



在我从一家公司收到这个OOP问题后,我轰炸了我的面试。你们中的一位专家可以使用Python帮助解决这个问题吗?我使用开关案例(使用 python 字典)在没有 OOP 的情况下解决这个问题。

Original string: abcdefghijklmn
Operations:F -> move curser forward, B -> move curse backward, R -> replace char
Operation string: F2B1F5Rw -> abcdefwhijklmn (expected output)
Moving forward by 2 chars, move backward by 1 char, move forward 5 chars, replace 1 char to be ‘w’
We can assume that curser is at first character at the beginning. How can I add more operations using OOP if required?

但显然面试官对我的转换案例方法不太满意,作为后续要求我使用 OOP 解决问题。任何想法如何在没有开关的情况下解决这个问题?使用 OOP 原则的更好方法还是我不知道的更好的数据结构?

"不满"背后的原因似乎不在于switch ... case或使用字典实现。对我来说,这似乎与OOP的概念有关。他/她可能希望您构建任务的OOP结构。

我将定义一个具有两个状态变量的类:一个用于当前字符串,一个用于当前位置。方法是对字符串施加的操作。例如,replace(char)(或下面的代码中的r(char))会将当前位置的字符替换为char。考虑到这些,我定义了一个名为Editor的类,从中创建对象,然后使用该对象。

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)
# could've just stored the list of chars (instead of string)
# from the beginning, but that's rather a secondary issue.
def run(self, command):
command = list(command)
while command:
method = getattr(self, command.pop(0).lower())
arg = command.pop(0)
method(arg)
def __str__(self):
return self.text
text = 'abcdefghijklmn'
command = 'F2B1F5Rw'
ed = Editor(text)
ed.run(command)
print(ed)

OOP 的一个优点是您可以灵活地向类添加更多不同的(字符)操作,例如上下转换。在我看来,这就是面试官所要求的。

您可以按如下方式执行此操作:

orig_string = 'abcdefghijklmn'
slist = list(orig_string)
opstr = 'F2B1F5Rw'
pos = 0
for w,p in zip(opstr[::2],opstr[1::2]):
if w == 'F': pos += int(p)
elif w == 'B': pos -= int(p)
elif w == 'R': slist[pos] = p
else: print ('Invalid Operational String... Aborting'); break
else:
print (''.join(slist))

您无需使用开关盒。您可以使用 if 语句并根据值处理当前位置。

如果值为:opstr = 'F2B1F5RwX2',则输出将为:Invalid Operational String... Aborting

相关内容

最新更新