【问题标题】:Recursion, out of memory?递归,内存不足?
【发布时间】:2016-11-15 02:47:05
【问题描述】:

我写了一个有两个参数的函数。一个是空字符串,另一个是字符串单词。我的任务是使用递归来反转单词并将其放在空字符串中。就在我想我明白的时候,我收到了“内存不足错误”。我编写了代码,以便它获取单词,将其转换为列表,将其向后翻转,然后将第一个字母放入空字符串中,然后从列表中删除该字母,以便递归可以发生在每个字母上。然后它将原始单词的长度与空字符串的长度进行比较(我制作了一个列表以便可以比较它们),以便当它们的等价物时递归将结束,但是 idk

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)  

【问题讨论】:

  • 这看起来不像是有效的 python 函数定义。 if 语句的底部附近是否存在格式问题?
  • 您不能将字母放在空字符串中;字符串是不可变的。当函数返回时,您对参数所做的任何更改都会随着该(局部)变量消失。

标签: python recursion


【解决方案1】:

在写递归的时候,我试着思考两件事

  1. 停止递归的条件
  2. 我希望一次迭代完成什么以及如何将该进度传递给下一次迭代。

另外,我建议让一个迭代工作,然后担心再次调用自身。否则会更难调试

无论如何,将其应用于您的逻辑

  1. 当输出字符串的长度与输入字符串的长度匹配时
  2. 将一个字母反向添加到新列表中。维护迄今为止积累的进度通行证列表

我想稍微修改你的代码,因为我认为这将帮助你学习最多......但我很难做到这一点,所以我试着写下我会用你的逻辑做什么。 希望您仍然可以从这个示例中学到一些东西。

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'))

这就是这段代码的递归样子

1.
character_index = 5-1 - 0
character_index is set to 4
output_list so far = ['o']
reverse_string('hello', ['o'])

2.
character_index = 5-1 - 1
character_index is set to 3
output_list so far = ['o', 'l']
reverse_string('hello', ['o', 'l'])

3.
character_index = 5-1 - 2
character_index is set to 2
output_list so far = ['o', 'l', 'l']
reverse_string('hello', ['o', 'l', 'l'])

4.
character_index = 5-1 - 3
character_index is set to 1
output_list so far = ['o', 'l', 'l', 'e']
reverse_string('hello', ['o', 'l', 'l', 'e'])

5.
character_index = 5-1 - 4
character_index is set to 0
output_list so far = ['o', 'l', 'l', 'e', 'h']
reverse_string('hello', ['o', 'l', 'l', 'e', 'h'])

6. lengths match just print what we have!
olleh

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 1970-01-01
    • 2012-06-15
    • 2016-05-05
    • 2017-03-15
    • 2014-03-24
    • 2023-04-09
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多