Python 递归,内存不足?
我写了一个有两个参数的函数。一个是空字符串,另一个是字符串字。我的任务是使用递归来反转单词并将其放入空字符串中。正如我所想,我收到了一个“内存不足错误”。我编写了代码,这样它就可以将单词转换成一个列表,将其向后翻转,然后将第一个字母放入空字符串中,然后从列表中删除该字母,以便对每个字母进行递归。然后,它将原始单词的长度和空字符串的长度进行比较(我列出了一个列表,以便对它们进行比较),这样当它们等价时,递归将结束,但idkPython 递归,内存不足?,python,recursion,Python,Recursion,我写了一个有两个参数的函数。一个是空字符串,另一个是字符串字。我的任务是使用递归来反转单词并将其放入空字符串中。正如我所想,我收到了一个“内存不足错误”。我编写了代码,这样它就可以将单词转换成一个列表,将其向后翻转,然后将第一个字母放入空字符串中,然后从列表中删除该字母,以便对每个字母进行递归。然后,它将原始单词的长度和空字符串的长度进行比较(我列出了一个列表,以便对它们进行比较),这样当它们等价时,递归将结束,但idk def reverseString(prefix, aStr):
def reverseString(prefix, aStr):
num = 1
if num > 0:
#prefix = ""
aStrlist = list(aStr)
revaStrlist = list(reversed(aStrlist))
revaStrlist2 = list(reversed(aStrlist))
prefixlist = list(prefix)
prefixlist.append(revaStrlist[0])
del revaStrlist[0]
if len(revaStrlist2)!= len(prefixlist):
aStr = str(revaStrlist)
return reverseString(prefix,aStr)
当我写一些递归的东西时,我试着思考两件事
def reverse_string(input_string, output_list=[]):
# condition to keep going, lengths don't match we still have work to do otherwise output result
if len(output_list) < len(list(input_string)):
# lets see how much we have done so far.
# use the length of current new list as a way to get current character we are on
# as we are reversing it we need to take the length of the string minus the current character we are on
# because lists are zero indexed and strings aren't we need to minus 1 from the string length
character_index = len(input_string)-1 - len(output_list)
# then add it to our output list
output_list.append(input_string[character_index])
# output_list is our progress so far pass it to the next iteration
return reverse_string(input_string, output_list)
else:
# combine the output list back into string when we are all done
return ''.join(output_list)
if __name__ == '__main__':
print(reverse_string('hello'))
当我写一些递归的东西时,我试着思考两件事
def reverse_string(input_string, output_list=[]):
# condition to keep going, lengths don't match we still have work to do otherwise output result
if len(output_list) < len(list(input_string)):
# lets see how much we have done so far.
# use the length of current new list as a way to get current character we are on
# as we are reversing it we need to take the length of the string minus the current character we are on
# because lists are zero indexed and strings aren't we need to minus 1 from the string length
character_index = len(input_string)-1 - len(output_list)
# then add it to our output list
output_list.append(input_string[character_index])
# output_list is our progress so far pass it to the next iteration
return reverse_string(input_string, output_list)
else:
# combine the output list back into string when we are all done
return ''.join(output_list)
if __name__ == '__main__':
print(reverse_string('hello'))
这看起来不像是有效的python函数定义。if语句底部附近是否存在格式问题?不能将字母放在空字符串中;字符串是不可变的。当函数返回时,对参数所做的任何更改都会随该(局部)变量一起消失。这看起来不像是有效的python函数定义。if语句底部附近是否存在格式问题?不能将字母放在空字符串中;字符串是不可变的。当函数返回时,对参数所做的任何更改都会随该(局部)变量一起消失。