找到递归函数的基本情况

时间:2014-04-10 12:05:45

标签: recursion

我正在尝试递归来计算每对()之间有多少个字符, 不计算其他()s中的字符。例如:

输入:

(abc(ab(abc)cd)(()ab))

输出:

Level 3: 3
Level 2: 4
Level 3: 0
Level 2: 2
Level 1: 3

“等级”指()嵌套的等级 - 等级3表示字符在一对内的一对内。

我的基本案例是什么?如果我理解正确的话,我问的问题是,“我怎么知道何时停止进行递归调用并开始解决它们?”

由于我没有在这篇文章中声明任何变量,因此伪代码是可以的。

1 个答案:

答案 0 :(得分:0)

我个人认为您的基本情况确实取决于您的实现和整体算法方法,因此您的问题并不是很完整。

尽管如此,我还是在Python中设计了一些东西,由于在基本情况下(额外处理而不是简单的返回)需要做的工作,所以它并不是很完美,但是对我来说足够好了。

def findParenthesis(subject):
if "(" in subject:
    start = subject.index("(")
    #slice string to remove extraneous characters
    sub_str = subject[(start + 1):]
    if ")" in sub_str:
        #reverse string so that closing bracket can be found more easily
        rev_sub = sub_str[::-1]
        print("reverse substring is: " + rev_sub)
        #considering that a reverse array is being scanned +1 for negative indexing and make negative
        end = -(rev_sub.index(")") + 1)
        print("end bracket located at: " + str(end))
        return (start, end)
return False

def countEach(subject, levels, rec_count):
    bracket_inds = findParenthesis(subject)
    if not bracket_inds:
        #since the normal recursion procedure measures characters outside of the brackets the inside needs to be measured as well before return
        levels.append(0)
        for mid_char in subject:
            if mid_char.isalpha():
                levels[rec_count] += 1
        return levels
    else:
        #generate the next array index so there are no invalid reference errors
        levels.append(0)
        #rereference for readability
        start, end = bracket_inds
        for pre_char in subject[:start]:
            #conditional for only finding alphabetic characters, not necessarily required
            if pre_char.isalpha():
                levels[rec_count] += 1
        for pst_char in subject[end:]:
            if pst_char.isalpha():
                levels[rec_count] +=1

        return countEach(subject[ (start + 1) : end ], levels, (rec_count + 1))

sample = "(abc(ab(abc)cd)(()ab))"

arr_out = []
rec_count = 0

print(countEach(sample, arr_out, rec_count))

最初,我没有使用正则表达式,而是沿"[\w\(\)]*\(([\w\(\)]+)\)[\w\(\)]*"的行使用正则表达式,将其作为参数'query'传递给countEach()和match.group(0)将是参数'subject '到下一个递归调用,因此当[compiled_regex].search(subject)返回None时,这将是基本情况。

但是您可以看到表达式不是很可读,所以我仍然可以这样做,但是总体复杂度类似