【问题标题】:Counting instances of a certain character in a string using recursion使用递归计算字符串中某个字符的实例
【发布时间】:2019-11-12 11:22:18
【问题描述】:

这个问题出现在我的期中考试中,我意识到我没有做对,所以我想知道我哪里错了。

我正在尝试定义一个函数 count_char(string, char),它使用递归返回 char 在 hello 中的总次数。


def count_char(string, char):
    #base case:
    if len(string) < 1:
        return
    #recursive case:
    if string[-1] == char:
        total = count_char(string[0:len(string)-1], char) + 1
    return total

当我运行count_char("hello", "h") 时,我得到一个错误:

UnboundLocalError: 赋值前引用了局部变量 'total'

我不确定我还能怎么做,这样总就不是局部变量了。

【问题讨论】:

  • 你在自己内部使用函数count_char()

标签: python function recursion


【解决方案1】:

如错误中所述,如果char 不在字符串中,则total 将尚未定义。您应该考虑的另一件事是字符串为空的情况,在这种情况下,您希望返回 0 以便它可以传播回递归堆栈。

考虑这个修改后的代码:

def count_char(string, char):
    #base case:
    if len(string) < 1:
        return 0
    #recursive case:
    if string[-1] == char:
        return count_char(string[0:len(string)-1], char) + 1
    return count_char(string[0:len(string)-1], char)

【讨论】:

    【解决方案2】:

    正如 Carcigenicate 所说,问题的出现是因为 if 条件不能保证为真,而 if 内部是函数中唯一声明和定义 total 的地方。

    这里有另一种方法:

    def count_char(string, char):
        #base case:
        if len(string) is 0:
            return 0
        #recursive case:
        total = int(string[-1] == char) + count_char(string[:-1], char)
        return total
    

    此外,从基本情况和递归情况返回 int 更加一致。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2013-07-21
      • 2012-10-04
      • 2013-11-15
      • 2014-04-06
      • 2014-03-31
      • 2014-03-31
      相关资源
      最近更新 更多