如何解决使用 OOP 解决这个问题的最佳方法是什么?
在我从一家公司得到这个面向对象的问题后,我轰炸了我的面试。你们中的一位专家可以使用 Python 帮助解决这个问题吗?我曾经使用 switch case(使用 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?
但显然面试官对我的 switch case 方法不太满意,并在后续要求我使用 OOP 解决问题。有什么想法可以在没有开关盒的情况下解决这个问题吗?使用 OOP 原则的更好方法还是我不知道的更好的数据结构?
解决方法
“不满意”背后的原因似乎不在于 switch ... case
或其使用字典的实现。对我来说,这似乎与更深层次的 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 的一个优点是您可以灵活地向类添加更多不同的(char-wise)操作,例如上下转换。在我看来,这就是面试官的要求。
,您可以按如下方式执行此操作:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。