繁体   English   中英

Python函数无法返回结果

[英]Python function unable to return result

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

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)

为了从递归函数中返回一个值,必须将return recursive_function(x)放到一个位置,以便在返回值时将其放置在函数可以在其上方访问数据的位置。 。

 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

您会看到,在此示例中,对于我来说,要保留先前传递的值,我必须返回它,以便在所有递归完成之后,它们都将把数据传递回功能链。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM