递归,内存不足?

时间:2016-11-15 02:47:05

标签: python recursion

我用两个参数编写了一个函数。一个是空字符串,另一个是字符串。我的任务是使用递归来反转单词并将其放在空字符串中。正如我认为的那样,我收到了一个"内存不足错误"。我编写代码,以便它接受单词,将其转换为列表,向后翻转它,然后将第一个字母放在空字符串中,然后从列表中删除字母,以便每个字母都可以进行递归。然后它将原始单词的长度与空字符串的长度进行比较(我创建了一个列表,以便对它们进行比较),这样当它们等效时递归将结束,但是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)  

1 个答案:

答案 0 :(得分:2)

在写一些递归的东西时,我会尝试思考两件事

  1. 停止递归的条件
  2. 我想要一次迭代,以及如何将该进度传递给下一次迭代。
  3. 此外,我建议让一次迭代工作,然后再担心再次调用自己。否则调试可能会更难

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

    1. 当输出字符串的长度与输入字符串的长度匹配时
    2. 反向添加一个字母到新列表。保持目前为止累积的进度通行证清单
    3. 我想稍微修改你的代码,因为我认为这将有助于你学习最多...但是很难用,所以我试着写下我对你的逻辑做什么。 希望你仍然可以从这个例子中学到一些东西。

      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