【问题标题】:Recursion Problem - breaking long sentence in multiple short strings递归问题 - 在多个短字符串中打破长句
【发布时间】:2019-10-26 20:54:53
【问题描述】:

如果它超过一定数量的单词,我正在尝试获取一个字符串并将其分成小块。 我不断收到 RecursionError:比较中超出了最大递归深度

我的代码中的什么导致了这种情况发生?

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)

【问题讨论】:

  • 你的句子的预期输出是什么?

标签: python-3.x recursion


【解决方案1】:

当您在 Python 中对较大的输入 (> 10^4) 执行递归函数时,您可能会遇到“超出最大递归深度错误”。 这里有递归:

  first = shorten(" ".join(sentence[:halfed]))
  second = shorten(" ".join(sentence[halfed:]))

这意味着一遍又一遍地调用同一个函数,它必须存储在一个堆栈中才能在某个地方返回,但看起来你的句子太长了,堆栈溢出并达到最大递归深度。 你必须对代码的逻辑做一些事情,比如将这个 6 增加到更大的数字

if length < 6:
  return [sentenceN]

或者只是增加递归深度

import sys 
sys.setrecursionlimit(10**6) 

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 2011-08-05
    • 2016-11-05
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多