递归函数产生堆栈溢出错误

问题描述 投票:0回答:3

我正在尝试解决作业问题:


Napieuler山脉的第一批探险者,在闲暇时间,通过喊出不同的短语来娱乐自己,听听回声是如何响起的。在他们的游戏中,他们注意到第一个回声总是原始短语的一小部分,第二个回声是第一个回声的相同部分,依此类推,直到一切都沉默。例如,在Napieuler地区,分数约为0.368。

当喊出100秒长的短语时,第一个回声是100 * 0.368秒长。第二个是100 * 0.368 * 0.368,依此类推,直到它难以察觉。写一个程序,在文本中近似于Napieuler山脉的回声。程序必须通过控制台接收它想要近似的回波的特征部分(作为单个十进制数)。然后程序必须调用一个递归函数,你应该收到一个短语。最后,你应该打印出短语的所有回声,包括人类大喊的原始短语。您还必须显示重复的总数,包括原始短语。由于您无法轻松计算书面短语的持续时间,因此您可以假设每个字母都需要一个恒定的时间,包括空格和标点符号。使用非整数结果舍入乘法。如果你在没有调用递归函数的情况下正确执行程序,那么问题就会为0。

你的功能需要

例子:

Enter the fraction: 0.369
Enter the sentence: I love mac and cheese
I love mac and cheese
cheese
se

回声总数:3

Enter the fraction: 0.369
Enter the sentence: Today it is not a beautiful spring day. I wish ot was.
Today it is not a beautiful spring day. I wish ot was.
day. I wish it was.
it was.
s.
Total of echoes: 4

我已经开始编写代码了,但是我一直遇到堆栈溢出错误。任何帮助,将不胜感激。

不断产生堆栈溢出错误的代码:

def echo(a,b):
    if len(b)>=2:
        return [b]+echo(a,b[(-(int(len(b)*a))):])
    else:
        return []

print(echo(0.369,"I love mac and cheese."))
python python-3.x recursion stack-overflow
3个回答
1
投票

len(b) == 2然后len(b) * a == 0.738,和int(len(b)*a)0-00相同,所以你用b[0:]进行递归调用,这与b相同,所以你无限地递归。

你需要在int(a * len(b)) == 0时停止递归。

def echo(a,b):
    newlen = int(len(b)*a)
    if newlen > 0:
        return [b]+echo(a,b[-newlen:])
    else:
        return [b]

print(echo(0.369,"I love mac and cheese"))

1
投票

您可以使用几行简单的代码自行调试。如果通过添加计数器将其限制为10次递归来人为限制代码堆栈溢出,并在每次递归调用中添加print语句以查看程序的状态,则可以轻松找出代码正在执行的操作并进行比较它符合您的期望:

def echo(a,b, counter=0):
    if counter < 10 and len(b)>=2:
        print('counter is: ', counter, ', I am using index: ', (-(int(len(b)*a))), ' which gives: ', b[(-(int(len(b)*a))):])
        return [b]+echo(a,b[(-(int(len(b)*a))):], counter+1)
    else:
        return []

在此调用print(echo(0.369,"I love mac and cheese."))给了我们:

counter is:  0 , I am using index:  -8  which gives:   cheese.
counter is:  1 , I am using index:  -2  which gives:  e.
counter is:  2 , I am using index:  0  which gives:  e.
counter is:  3 , I am using index:  0  which gives:  e.
counter is:  4 , I am using index:  0  which gives:  e.
counter is:  5 , I am using index:  0  which gives:  e.
counter is:  6 , I am using index:  0  which gives:  e.
counter is:  7 , I am using index:  0  which gives:  e.
counter is:  8 , I am using index:  0  which gives:  e.
counter is:  9 , I am using index:  0  which gives:  e.
['I love mac and cheese.', ' cheese.', 'e.', 'e.', 'e.', 'e.', 'e.', 'e.', 'e.', 'e.']

这意味着,正如Joran所说,你最终无限地计算这件作品:

'e.'[0:]

总是评估为'e.'

有了这些知识,我相信你将能够弄清楚如何修复你的代码。


0
投票

在你的最后一次迭代你有e.

这是len 2

你做echo(a,b[-0:])

实际上评估为echo(a,b[0:])

e.再次调用它

您需要更改的2个字符(一个删除和一个插入)将更正您的代码

© www.soinside.com 2019 - 2024. All rights reserved.