下面是一个函数,它应该返回一个字符串的最长回文子串。虽然函数本身看起来没问题,但出于某种奇怪的原因,它没有返回字符串。知道我在这里缺少什么吗?
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
你看到在这个例子中,我要保存之前传递的值,我必须返回它,这样在所有递归完成后,它们都会将数据传递回函数链。
关于Python函数无法返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467618/