Python 3.x 使用OOP解决这个问题的最佳方法是什么?

Python 3.x 使用OOP解决这个问题的最佳方法是什么?,python-3.x,oop,data-structures,Python 3.x,Oop,Data Structures,当我从一家公司得到这个OOP问题后,我的面试失败了。你们中的一位专家能用Python帮助解决这个问题吗?我使用了switch cases(使用python字典)来解决这个问题,而不使用OOP Original string: abcdefghijklmn Operations:F -> move curser forward, B -> move curse backward, R -> replace char Operation string: F2B1F5Rw -&g

当我从一家公司得到这个OOP问题后,我的面试失败了。你们中的一位专家能用Python帮助解决这个问题吗?我使用了switch cases(使用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原则的更好方法,或者我不知道的更好的数据结构?

这种“不满”背后的原因似乎不在于开关。。。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的一个优点是,您可以灵活地向类添加更多不同的(字符)操作,如上下转换。在我看来,这正是面试官的要求。

你可以这样做:

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语句,并根据值处理当前位置


如果值为:
optstr='F2B1F5RwX2'
,则输出将为:
无效的操作字符串。。。中止

很好的解决方案。但是我在寻找一种面向对象的方法,所以我接受了另一种方法。当然。我同意@j1 lee提供的解决方案。这就是面向对象的解决方案。我给了你一个解决这个问题的方法,这样你就知道如何把它转换成面向对象的。好的解决方案。您是否也可以处理输入可能不是F、B或R的场景。@JoeFerndz这是一个很好的建议,但我将把该任务留给OP;)