递归python脚本

时间:2015-09-04 06:47:17

标签: python

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)

所以我对递归很新,我知道有一种更简单的方法可以做到这一点但有人可以解释如何解决这个问题。这基本上是一个递归函数来查找字母的总次数&# 39; 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,      

在         新(final_text)     RuntimeError:超出最大递归深度

所以它有效,但它继续循环。我会让它停止 提前谢谢你

1 个答案:

答案 0 :(得分:6)

< len(s)

这种情况永远不会成立,因为str.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

请注意,对这样的函数使用全局变量,尤其是递归函数,是一个坏主意。您无法完全控制它,相反,您还需要确保在调用该函数时重置其值。相反,您应该保留所有信息,并在必要时将其传递给递归调用。您可以像这样更改您的功能:

found

这使用默认参数值来确保found以0开头。对于递归调用,它只传递新的'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 的索引:

var folderToCreate = "D:\\Temp\\www.domain.com";
imns.FIO.makeDirectory(folderToCreate);

最后,如果您不知道,还有一个内置函数str.count执行相同的操作:)