递归Python简单函数

时间:2015-08-10 01:07:35

标签: python string function recursion

我正在进行CS类的MIT简介以学习python并且遇到了涉及递归编程的问题集(在其自身内部调用函数)。目标是找到给定目标字符串的多个事件。我有以下代码,从我的逻辑来看,它似乎应该但我无法弄清楚它为什么没有!任何帮助深表感谢。感谢。

def countSubStringMatchRecursive(target,key):
    answers = []
    match = target.find(key)

    if match != -1:
        answers.append(match)
        next_target = target[match+1:]
        countSubStringMatchRecursive(next_target,key)

    return len(answers)

所以对于给定的论点:

target1 = 'mjzzmjzzmj'
key1 = 'zz'

print(countSubStringMatchRecursive(target1, key1))

我得到1而不是2的正确答案。

这是Python3顺便说一句。

2 个答案:

答案 0 :(得分:2)

既然你不需要答案......你不需要答案;只是一个计数。

from __future__ import print_function


def countSubStringMatchRecursive(target, key):
    match = target.find(key)

    if match != -1:
        next_target = target[match+1:]
        return 1 + countSubStringMatchRecursive(next_target, key)
    else:
        return 0


print(countSubStringMatchRecursive('asd asd asd', 'sd'))  # 3
print(countSubStringMatchRecursive('ababa', 'ab'))  # 2

这会计算重叠的匹配数;如果那不是你想要的,请告诉我。

答案 1 :(得分:0)

导致你的变量"回答"是在功能的主体。因此,每次调用该函数时,它都会被重置为" answer = []"

answers=[]

def countSubStringMatchRecursive(target,key):
    match = target.find(key)

    if match != -1:
        global answers
        answers.append(match)
        next_target = target[match+1:]
        countSubStringMatchRecursive(next_target,key)

    return len(answers)

target1 = 'mjzzmjzzmj'
key1 = 'zz'

print(countSubStringMatchRecursive(target1, key1))