2013-10-17 62 views
0

我正在嘗試編寫遞歸函數時遇到問題。它看起來像功能不下降。我沒有收到任何錯誤或任何信息,所以我並沒有真正瞭解發生了什麼。我從中得到的唯一結果是一些空的列表。本質上,我試圖跟蹤我的程序可以通過一些給定輸入採取的所有路徑,並返回一個包含所有這些路徑的列表。我對python真的很新,所以有很多我不知道。我也是新的stackoverflow,所以原諒格式錯誤。提前致謝!Python遞歸函數不降序

def Process (fst, input, start_state, current_path=[], input_index=0): 
    current_line = input.replace('"', '') 
    current_state = start_state 
    probability = 1 
    result = [] 
    state_paths = [] 
    this_path = current_path 
    paths_found = [] 
    epsilon_paths_found = [] 
    temp_list = [] 
    index = input_index 


    if not index < len(current_line): 
     return this_path 

    item = current_line[index] 

    if not item.isspace(): 
     for edge in fst.transitions[current_state]: 
      next_state = current_state 
      if item == edge.input: 
       paths_found.append(edge) 
       index += 1 
      for x in paths_found: 
       temp_list = this_path 
       temp_list.append(x) 
       temp_entry = Process(fst, input, x.target_state, temp_list, index) 
       state_paths.append(temp_entry) 

      #epsilon returns a list 
      epsilon = EpsilonStates(fst.transitions[current_state]) 

      if epsilon: 
       index -= 1 
       for i in epsilon: 
        epsilon_paths_found.append(i) 
       for y in epsilon_paths_found: 
        temp_list = this_path 
        temp_list.append(y) 
        state_paths.append(Process(fst, input, y.target_state, temp_list, index)) 
    return state_paths 
+0

你能解決這個缺口?這裏不清楚'Process'的定義結束和頂層模塊代碼的開始 - 這對於回答你的問題是至關重要的。 – abarnert

+0

更好嗎? –

+0

這取決於。這是你的實際代碼嗎?因爲當我嘗試它時,在它甚至可以運行任何東西之前我會得到一個'IndentationError' ... – abarnert

回答

-2

對於發生遞歸,您的過程函數需要調用它自己。通常使用初始函數參數的子集。

在您的代碼中,您正在從for循環調用Process函數。所以這不會是遞歸的。

這個討論有一個遞歸函數的例子,以及爲什麼論點,在後續調用降低了一個例子:

How can I build a recursive function in python?

+0

所以我需要從任何循環之外調用它? –

+0

從循環內調用它是無關緊要的。如果該循環位於函數體內部,則它是遞歸的。如果它在函數體外,那不是。 – abarnert

+0

對不起,我還沒有關注... –