【问题标题】:Python Maximum depth recursion error - issue with base casePython最大深度递归错误 - 基本情况问题
【发布时间】:2015-09-25 11:48:03
【问题描述】:

我写了一个python函数replace_str,它消耗3个非空字符串,base、target和rep。

第一个字符串 base 表示要更新的基本字符串。第二个字符串 target 表示要替换的目标字符串,第三个字符串 rep 表示将替换更新字符串中的目标的字符串。

该函数生成一个新字符串,其中目标字符串被基础字符串中的 rep 字符串替换,但如果以下任一条件成立,则生成相同的基础字符串。

• 如果在基本字符串中找不到目标字符串,或者,

• 如果目标和代表是相同的字符串。

不允许使用字符串方法替换和查找

这是我目前所拥有的:

def replace_str(base, target, rep): 
    m = 0
    n = len(target)
    if base[m:n] == target:
        new_base = base[0:m] + rep + base[n:]
        return replace_str(new_base, target, rep)
    else:
        m = m + 1
        n = n + 1
        return replace_str(base, target, rep)

我在测试程序时遇到最大递归深度错误。我正在尝试各种基本情况,因为那是我的函数卡住的地方,但我尝试的所有基本情况都给我 '' 或基数的最后一个字母

replace_str("aaaax","aa","x") 应该产生 'aax' 但给我一个错误。

replace_str("aa", "aa", "x") 但是给了我'x' 的正确结果。

另外,这篇文章与另一篇文章不重复。带有链接帖子的程序完全不同,并且有不同的问题。我的基本情况有问题。

【问题讨论】:

  • m = m + 1 没用,因为之后不再使用m。考虑拨打return base[0] + replace_str(base[1:], target, rep)
  • 如果您告诉我们您正在测试哪些字符串会产生此错误,这将很有用。
  • 两个分支总是会再次调用replace_str。它永远无法逃脱。
  • 您没有基本情况。这里根本没有返回结果的代码路径。你的 return 语句总是调用函数,所以你无限递归。
  • 看看你上面的评论。你永远不会返回任何东西。使用递归,您总是必须有一个终止或基本情况,其中返回一些具体的东西。你只能递归调用函数,所以它会无限递归

标签: python string recursion runtime-error


【解决方案1】:

在您的else 分支中,您更新了mn,但您不能将这些值传递给对replace_str 的下一次调用,这最终会从头开始。

您需要添加 mn 作为参数,或者将函数的那部分转换为循环。

使用额外的参数更容易,看起来像这样:

# adding m and n as arguments
def replace_str(base, target, rep, m=0, n=None):
    if n is None:
        n = len(target)
    ...

您还需要一个基本案例,其中最简单的可能是:

# adding m and n as arguments
def replace_str(base, target, rep, m=0, n=None):
    if target not in base:
        return base
    if n is None:
        n = len(target)
    ...

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多