Python 3.x 递归问题-在多个短字符串中打断长句
我试着把一个字符串,如果超过一定的字数,就把它分成小块。 我不断得到一个递归错误:相比之下,超过了最大递归深度 在我的代码中是什么让这发生的Python 3.x 递归问题-在多个短字符串中打断长句,python-3.x,recursion,Python 3.x,Recursion,我试着把一个字符串,如果超过一定的字数,就把它分成小块。 我不断得到一个递归错误:相比之下,超过了最大递归深度 在我的代码中是什么让这发生的 import math # Shorten Sentence into small pieces def shorten(sentenceN): # If it is a string - and length over 6 - then shorten recursively if (isinstance(sentenceN, str)):
import math
# Shorten Sentence into small pieces
def shorten(sentenceN):
# If it is a string - and length over 6 - then shorten recursively
if (isinstance(sentenceN, str)):
sentence = sentenceN.split(' ')
array = []
length = len(sentenceN)
halfed = math.floor(length / 2)
if length < 6:
return [sentenceN]
# If sentence is long - break into two parts then rerun shorten on each part
else:
first = shorten(" ".join(sentence[:halfed]))
second = shorten(" ".join(sentence[halfed:]))
array.append(first)
array.append(second)
return array
# If the object is an array (sentence is already broken up) - run shorten on each - append
# result to array for returning
if(isinstance(sentenceN, list)):
array = []
for sentence in sentenceN:
array.append(shorten(sentence))
return array
# example sentences to use
longSentence = "On offering to help the blind man, the man who then stole his car, had not, at that precise moment."
shortSentence = "On offering to help the blind man."
shorten(shortSentence)
shorten(longSentence)
导入数学
#把句子缩短成小块
def缩短(句子):
#如果它是一个字符串,长度超过6,则递归地缩短
如果(isinstance(语句,str)):
句子=句子拆分(“”)
数组=[]
长度=长度(句子)
一半=数学地板(长度/2)
如果长度小于6:
返回[句子]
#如果句子是长的-分成两部分,然后在每一部分上重新运行shorten
其他:
第一个=缩短(“.”连接(句子[:一半])
第二个=缩短(“.”连接(句子[halfed:]))
array.append(第一个)
array.append(第二个)
返回数组
#如果对象是一个数组(句子已经被分解)-在每个数组上运行shorten-append
#将结果发送到数组以返回
如果(isinstance(语句,列表)):
数组=[]
对于句子中的句子:
array.append(缩短(句子))
返回数组
#要使用的例句
longSentence=“在主动提出帮助盲人的时候,那个后来偷了他的车的人,当时还没有。”
Short句子=“表示愿意帮助盲人。”
缩短(短句)
缩短(长距离)
在大型输入(>10^4)上用Python执行递归函数时,可能会遇到“超出最大递归深度错误”。
这里有递归:
first = shorten(" ".join(sentence[:halfed]))
second = shorten(" ".join(sentence[halfed:]))
这意味着一遍又一遍地调用同一个函数,它必须存储在堆栈中才能在某个地方返回,但您的语句似乎太长,堆栈溢出并达到最大递归深度。
您必须对代码的逻辑进行一些处理,比如将这个6增加到一个更大的数字
if length < 6:
return [sentenceN]
你的句子的预期输出是什么?
import sys
sys.setrecursionlimit(10**6)