簡體   English   中英

遞歸函數產生堆棧溢出錯誤

[英]Recursive Function Produces Stack-Overflow Error

我正在嘗試解決作業問題:


納皮厄勒山脈的第一批探險家在閑暇時通過喊叫不同的短語來娛樂自己,聽回聲的響聲。 在游戲中,他們注意到第一個回聲總是原始短語的一小部分,第二個回聲則是第一個回聲的相同部分,依此類推,直到所有內容都保持沉默為止。 例如,在納皮厄勒地區,分數約為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."))

您可以使用幾行簡單的代碼自行調試。 如果您通過添加一個計數器將其限制為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.'

有了這些知識,我相信您將能夠弄清楚該如何解決您的代碼。

len(b) == 2 len(b) * a == 0.738 ,並且int(len(b)*a)0 -0是一樣的0 ,那么你正在做與遞歸調用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"))

在最后一次迭代中,您有e.

len 2

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

實際上評估為echo(a,b[0:])

e.再次調用它e.

您需要更改2個字符(一次刪除一次插入)即可更正您的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM