Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用递归计算字符串中某个字符的实例_Python_Function_Recursion - Fatal编程技术网

Python 使用递归计算字符串中某个字符的实例

Python 使用递归计算字符串中某个字符的实例,python,function,recursion,Python,Function,Recursion,这个问题出现在我的期中考试中,我意识到我做得不对,所以我想知道我哪里做错了 我试图定义一个函数count\u char(string,char),它使用递归返回char在hello中的总次数 def计数字符(字符串,字符): #基本情况: 如果len(字符串)

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

我试图定义一个函数
count\u char(string,char)
,它使用递归返回char在hello中的总次数


def计数字符(字符串,字符):
#基本情况:
如果len(字符串)<1:
返回
#递归情况:
如果字符串[-1]==字符:
总计=计数字符(字符串[0:len(字符串)-1],字符)+1
返回总数
当我运行
count\u char(“hello”,“h”)
时,我得到一个错误:

UnboundLocalError:分配前引用的局部变量“total”


我不确定如何才能使total不是局部变量。

如错误中所述,如果字符串中没有
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)
def count_char(字符串,char):
#基本情况:
如果len(字符串)<1:
返回0
#递归情况:
如果字符串[-1]==字符:
返回计数字符(字符串[0:len(string)-1],字符)+1
返回计数字符(字符串[0:len(string)-1],字符)

正如Carcigenicate所说,问题的产生是因为
if
条件不能保证为真,而
if
内部是函数中声明和定义
总计的唯一位置

以下是另一种方法:

def count_char(字符串,char):
#基本情况:
如果len(字符串)为0:
返回0
#递归情况:
总计=int(字符串[-1]==char)+count_char(字符串[:-1],char)
返回总数

此外,从基本大小写和递归大小写返回一个
int
更为一致。

您在其内部使用函数
count\u char()