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)
Run Code Online (Sandbox Code Playgroud)
所以我是递归的新手,我知道有一种更简单的方法可以做到这一点,但是有人可以解释如何解决这个问题.这基本上是一个递归函数来查找字母'x'可以找到的总次数变量'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,
Run Code Online (Sandbox Code Playgroud)
in new(final_text)RuntimeError:超出最大递归深度
所以它的工作原理,但它继续循环.我会提前停止它
found > len(string)
Run Code Online (Sandbox Code Playgroud)
这种情况永远不会成立,因为它str.find总会返回一个结果< len(s).
没有结果时检查的正确返回值是-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
Run Code Online (Sandbox Code Playgroud)
请注意,对这样的函数使用全局变量,尤其是递归函数,是个坏主意.您无法完全控制它,相反,您还需要确保在调用该函数时重置其值.相反,您应该保留所有信息,并在必要时将其传递给递归调用.你可以像这样改变你的功能:
def new (string, found = 0):
fish = string.find('x', found)
if fish < 0:
return 0
return new(string, fish + 1) + 1
Run Code Online (Sandbox Code Playgroud)
这使用默认参数值来确保found以0开头.对于递归调用,它只传递新found值,因此下一个函数可以从那里开始.
最后请注意,您应该尝试为函数和变量使用描述性名称.该函数应该计算出现次数'x',所以可能count_x会更好.此外,该found上下文中的变量传达了一个含义,即它包含x您已经找到的出现次数; 但相反,它是继续搜索的起始偏移量; 并且fish很糟糕,因为它只是下一个的索引'x':
def count_x (string, offset = 0):
index = string.find('x', offset)
if index < 0:
return 0
return count_x(string, index + 1) + 1
Run Code Online (Sandbox Code Playgroud)
最后,如果您不知道,还有一个内置函数str.count,它做同样的事情:)