Python函数无法返回结果

时间:2017-02-26 10:57:38

标签: python algorithm python-3.x

下面是一个函数,它应该返回一个字符串的最长回文子串。虽然函数本身看起来不错但是由于一些奇怪的原因它没有返回字符串。知道我在这里缺少什么吗?

def largest(string, repeat=None):
    if len(string) <= 1 and repeat:
        return repeat[max(repeat.keys())]
    elif len(string) <= 1:
        return string
    list_str = list(string)
    repeat = repeat or {}
    end_index = -1
    while len(list_str)+end_index:
        construct = list_str[0:len(list_str)+end_index+1]
        reversed_construct = construct.copy()
        reversed_construct.reverse()
        if construct == reversed_construct:
            repeat[len(construct)] = ''.join(construct)
        end_index -= 1
    string = string[1:]
    largest(string, repeat=repeat)

1 个答案:

答案 0 :(得分:1)

为了从递归函数返回一个值,必须放置return recursive_function(x),以便在返回值时将其放置在可以通过上面的函数& #39;可以这么说。

 def Factorial(total,counter):
    if counter == 0:    #tests whether the counter is at 0
        return(total)   #if it is at 0 return the product of the consectutive numbers between 0 and starting counter
    total *= counter    #set the total to itself times the current pass counter
    return Recursion(total,(counter-1)) #return the value of this function passing the total and the counter -1

你看到在这个例子中,我保持先前传递的值,我必须返回它,以便在完成所有递归后,它们都将数据传递回函数链。