首页 > 解决方案 > 最大递归深度

问题描述

我不断获得最大递归深度,但我不知道如何解决它。有人可以帮助我吗?这是我的代码:

with open("input.txt") as file:

    def remove_string_recursive():

        with open("input.txt") as file:

            for line in file:

                string, letter = line.strip().split(",")
 
                if (len(string) == 0): 
                    return "" 

                if (string[0] == letter): 
 
                    return remove_string_recursive() 

                return string[0] + remove_string_recursive() 

string = remove_string_recursive() 
  
print(string + "," + letter) 

如果有帮助,我的代码将具有与以下相同的输入和输出,但使用递归格式。

with open("input.txt") as file:

    def remove_from_string():

        with open("input.txt") as file:
    
            for line in file:

                string, letter = line.strip().split(",")
   
                res_str = string.replace(letter, '') 
   
                print (res_str + "," + letter)

remove_from_string()

标签: python

解决方案


编码二战答案。

代码

def remove_strings_recursive(lines):
    # Base Case
    if not lines:
        return ""
    
    # with the first item in the list
    # split it on a comma into a word and a letter
    word,letter = lines[0].rstrip().split(',')
    
    # remove all instance of the letter from the word
    word = word.replace(letter, '')
    
    # recurse by returning the word and calling the function with list_of_lines[1:]
    # placing a carriage return between each result 
    return word + '\n' + remove_strings_recursive(lines[1:])

# open the file (just once!)
with open('input.txt', 'r') as file:
    # read all the lines into a list
    lines = file.readlines()
    
    # call the function with the list_of_lines as the argument
    result = remove_strings_recursive(lines)
    print(result)  # Output result to console

测试

文件输入.txt

banana,a
roberto,o
bookkeeper,e
cheerlessness,s
mississippi,i

输出

bnn
rbert
bookkpr
cheerlene
msssspp

推荐阅读