python - 最大递归深度
问题描述
我不断获得最大递归深度,但我不知道如何解决它。有人可以帮助我吗?这是我的代码:
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()
解决方案
编码二战答案。
代码
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
推荐阅读
- javascript - JQuery - 删除字符后的文本,保持字符串逗号分隔
- css - 如何通过 React-Joyride 垂直居中目标元素
- outlook-addin - Outlook 插件清单文件
- amazon-web-services - java.io.IOException:方案没有文件系统:s3
- node.js - ERR_INVALID_ARG_TYPE “数据”参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例。收到未定义。仅在 Docker 上
- azure - Azure VNET:向微软公共 IP 发送流量
- reactjs - React 路由器选项卡在 wordpress 自定义子菜单页面上不起作用
- java - 使用 feign 进行慢速并行调用
- node.js - Express.js,如果我的参数值在某个值的某处包含冒号,我会在值的前面加上冒号
- c++ - c/c++是否定义有符号整数除法的结果:负极除以负1(INT_MIN/-1)