【问题标题】:Python 3 recursive method returning last value not current valuePython 3递归方法返回最后一个值而不是当前值
【发布时间】:2021-09-11 05:53:18
【问题描述】:

我对这个有点难过。我正在做一个 leet 代码问题,用于从字符串中删除重复的字符。我对这个问题采取了递归方法,但是我的输出没有遵循预期的行为,我不确定为什么。希望这里有人可以解释我所缺少的。

输入:s = "azxxzy" 预期输出:“ay”

说明:在查看 azxxzy 时,我们首先删除相邻的 xx 字符。这让你眼花缭乱。然后你可以删除 zz,只留下 ay,没有其他相邻的重复字符。

我为此编写的代码。

def removeDuplicates(s: str):
    i =  0
    while i < len(s) - 1:
        if s[i] == s[i+1]:
            s = s.replace(s[i] + s[i+1], '')
            removeDuplicates(s)
        i += 1
    return s

这将返回“azzy”作为结果。

但是,如果我放入一些打印语句来跟踪 s 的值。在返回声明之前,它似乎工作正常。

def removeDuplicates(self, s: str) -> str:
    i =  0
    print(s)
    while i < len(s) - 1:
        if s[i] == s[i+1]:
            s = s.replace(s[i] + s[i+1], '')
            removeDuplicates(s)
        i += 1
    print(s)
    return s

返回:

azxxzy    - Starting Value
azzy      - Value after first recursive call
ay        - Value after second recursive call
ay        - No duplicates found, so it just prints the value of s
ay        - No duplicates found, so it just prints the value of s
azzy      - Python decides it wants to grab the last value of s for some reason!?!

【问题讨论】:

  • 如果您有“azxzxy”,则无法删除相邻的重复项。
  • @j1-lee 成功了。完全忽略了这一点,因为值在打印语句中按预期更新。
  • @DavidLee 没错,它只应该删除存在相邻重复项的字符,而不仅仅是重复值。抱歉,如果我没有说清楚在您的示例中没有相邻的重复项,因此返回值将只是 azxzxy。
  • 即使递归版本终于可以工作了,它也不是很有效。使用 stack 跟踪重复项会快得多。

标签: python python-3.x recursion


【解决方案1】:

感谢 j1-lee 的解释。我没有返回递归函数调用的结果。下面的代码现在按预期工作。

def removeDuplicates(self, s: str) -> str:
    i =  0

    while i < len(s) - 1:
        if s[i] == s[i+1]:
            s = s.replace(s[i] + s[i+1], '')
            s = removeDuplicates(s)
        i += 1

    return s

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 2021-12-31
    • 2021-05-24
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多