递归python脚本
所以我对递归很陌生,我知道有一种更简单的方法可以做到这一点,但是有人能解释一下如何解决这个问题吗。这基本上是一个递归函数,用于计算在变量“text”中可以找到字母“x”的总次数递归python脚本,python,Python,所以我对递归很陌生,我知道有一种更简单的方法可以做到这一点,但是有人能解释一下如何解决这个问题吗。这基本上是一个递归函数,用于计算在变量“text”中可以找到字母“x”的总次数 found = 0 def new(string): global found if found > len(string): return 0 fish = string.find('x',found,len(string)) found = fish + 1
found = 0
def new(string):
global found
if found > len(string):
return 0
fish = string.find('x',found,len(string))
found = fish + 1
return new(string) + 1
text = 'onxonxoinxoinoxn'
final_text = text + 'x'
print new(final_text)
在
新增(最终文本)
运行时错误:超过最大递归深度
所以它工作了,但它继续循环。我如何使它停止
先谢谢你
This is my error:
4
7
11
16
18
0
4
7
Traceback (most recent call last):
11
16
File "/Users/Charana/Documents/Projects/untitled/Main.py", line 18,
此条件永远不会为真,因为将始终返回结果
没有结果时要检查的正确返回值为-1
。但是您需要小心增量,因为这会将无效结果-1
更改为0
继续循环。因此,您应该重新排列您的逻辑:
found > len(string)
最后,以防您不知道,还有一个内置函数可以做同样的事情:)您应该测试
fish
不是-1
,因为这意味着不再有x
(并退出)。在您的情况下,found
获取fish+1
,即0
,因此重新启动。非常感谢。但是这听起来可能很愚蠢,但是为什么if
语句fish<0
在字符串末尾时得到满足。难道fish<0
不适用于字符串中的每个字母吗?为什么当它到达最后一个“x”时,字符串的最后一个字符具有索引len(string)-1
(因为第一个字符位于索引0处);而string.find()
返回该字符的索引,或者在字符串中找不到该字符时返回-1
。因此,我们检查-1
(或者<0
)以确定字符串中是否存在匹配项。
def new(string):
global found
fish = string.find('x',found,len(string))
if fish < 0:
return 0
found = fish + 1
return new(string) + 1
def new (string, found = 0):
fish = string.find('x', found)
if fish < 0:
return 0
return new(string, fish + 1) + 1
def count_x (string, offset = 0):
index = string.find('x', offset)
if index < 0:
return 0
return count_x(string, index + 1) + 1