【问题标题】:What would be the best approach to solve this using OOP? [closed]使用 OOP 解决此问题的最佳方法是什么? [关闭]
【发布时间】:2021-03-30 05:18:07
【问题描述】:

在我从一家公司收到这个 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 原则的更好方法,或者我不知道的更好的数据结构?

【问题讨论】:

    标签: python-3.x oop data-structures


    【解决方案1】:

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

    【讨论】:

    • 很好的解决方案。您是否还可以处理输入可能不是 F、B 或 R 的情况。
    • @JoeFerndz 这是一个很好的建议,但我会把这个任务留给 OP ;)
    【解决方案2】:

    你可以这样做:

    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

    【讨论】:

    • 不错的解决方案。但我一直在寻找一种 OOP 方法,因此接受了另一种方法。
    • 当然。我同意@j1-lee 提供的解决方案。这就是 OOP 解决方案。我给了你一个解决这个问题的方法,所以你知道如何将它转换为 OOP。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 2011-11-10
    相关资源
    最近更新 更多