2016-11-29 31 views
0

例如,我有這樣的函數:如何計算該函數內的函數調用時間以及可以在Python中恢復的數量?

def a (x): 
    f(x) 
    if f(x) < 0: 
     a(x) # If a(x) is called over 30 times, then stop calling a(x) and return certain value. 
    else: return f(x) 

我要計算功能的if語句下撥打的號碼。一旦主叫號碼超過了某個號碼,我就可以停止運行一個(x)並返回特定的值,並且可以恢復主叫號碼。

我該怎麼做?常規計數包裝器是用於整個功能的,這在我看來不適合這種情況?

------------更新-------------

由於@Yevhen Kuzmovych現在我有一個例子功能是這樣的:

def a (x, depth = 0): 
    b = x - 1 
    print(depth, b) 
    if b < 0: 
     if depth < 10: 
      a(b, depth + 1) 
     else: 
      return b 
    else: 
     return b 

c = a(0) # this doesn't have a value 

所以使用這個函數,c沒有值。我不明白。它似乎沒有返回價值。

+1

在if語句中使用「counter」。即。 '如果計數器<30:計數器+ = 1; a(x)' – furas

+0

@MoinuddinQuadri是的,正好。因爲這可能是一個死循環,所以我想在if語句下跟蹤'a(x)'的計數器,並在返回'某個值'時恢復計數器 – user3716774

回答

1

你需要計算遞歸的深度:

def a(x, depth = 0): 
    f(x) 
    if f(x) < 0: 
     if depth < certain_number: 
      return a(x, depth + 1) 
     else: 
      return certain_value 
    else: 
     return f(x) 
+0

非常感謝您的回覆,但我有現在代碼存在問題。看起來'certain_value'沒有正確返回。我怎樣才能得到這個'確定的價值'? – user3716774

+0

@ user3716774當您調用'a()'時添加'return'。更新了答案。 –

+0

是啊!非常感謝!! – user3716774

0

遞歸(調用函數中的一個函數)是有用的時候,但是在這種情況下,很容易避開它,可能會更快地做到這一點。在Python中,您只能在RuntimeError: maximum recursion depth exceeded while ...之前進行970次函數調用。

這樣做的一種迭代方法是僅在for循環中使用範圍,其中times變量是「主叫號碼」(或該功能被調用了多少次)。

def a(x, retry=0): 
    for times in range(1, retry + 1): # xrange in Python 2 
     processed = f(x) # Store the value so you don't need to call f(x) again 
     if processed < 0: 
      continue # Try again, having gone through one more item in the range 
     return processed 
    return certain_value # You only get here if the range runs out 
相關問題