2017-08-14 88 views
-2

我一直在使用递归编写的代码,但后来意识到,深度过大和更高层次的输入值不起作用。它工作得很好,没有任何问题。递归工作,但不与循环

def checkCount(first_window, index=0,reference_list=None): 
    reference_list = [] 
    count = 0 
    while index<=len(first_window)-2: 
     if first_window[index] < first_window[index+1]: 
      index += 1 
      count += 1 
     else: break 
    if count != 0: 
     reference_list.append(int((count*(count+1))/2)) 

    count = 0 
    while index <= len(first_window)-2: 
     if first_window[index] > first_window[index+1]: 
      index += 1 
      count += 1 
     else: break 
    if count != 0: 
     reference_list.append(-int((count*(count+1))/2)) 

    if index > len(first_window)-2: return reference_list 
    elif first_window[index] == first_window[index+1] and index<len(first_window)-2: index += 1 

    reference_list = reference_list + checkCount(first_window, index, reference_list) 
    return reference_list 

import random 
import time 
start = time.clock() 
input_array = list(map(int,"188930 194123 201345 154243 154243".split(" "))) 
input_array = random.sample(range(1,100),10) 

def main(): 

    N = len(input_array) 
    K = 8 
    if K == 1: return None 

    print("Input array: ",input_array) 
    print("First Window",input_array[:K]) 
    print("Real Output", checkCount(input_array[:K])) 
if __name__ == "__main__":main() 

现在不管我如何尝试没有递归,它以无限循环结束。我尝试过不同的方式,但没有进步。我曾尝试

一种方法是取出递归语句,并返回referencelist +指数:

def checkCount(..): 
    .... 
    .... 
    return referencelist,index 



while index <= K-2: 
    print("While",index) 
    reference_list, index = checkCount(new_input, index=0, reference_list=[]) 
    referencelist += reference_list 

应用类似于here。但是,我们必须处理递归无法帮助的大量数据。假设输入数组大于100,000。我非常震惊,我不明白我错过了什么逻辑。任何帮助将不胜感激。

+0

你可以简化这个吗?看看如何创建[mcve]。 –

+0

你的递归看起来是颠倒的。你需要a)**一个终端条件**和b)**调用自己的函数减少工作量**尝试重新考虑它减少到零。 – quadruplebucky

+0

@quadruplebucky我放弃了递归因为不管我做什么,它最后用大递归深度和Python不支持超过1000深度通话结束。尝试用增量步骤调用递归函数,但它使其他方法的工作更复杂。 –

回答

2

first_window变量是只读的,并且索引变量只递增。不需要递归,简单的循环就可以工作。

def check_count(first_window): 
    reference_list = [] 
    index = 0 
    while index < len(first_window) - 2: 
     count = 0 
     while index <= len(first_window) - 2: 
      if first_window[index] < first_window[index + 1]: 
       index += 1 
       count += 1 
      else: 
       break 
     if count != 0: 
      reference_list.append(int((count * (count + 1))/2)) 

     count = 0 
     while index <= len(first_window) - 2: 
      if first_window[index] > first_window[index + 1]: 
       index += 1 
       count += 1 
      else: 
       break 
     if count != 0: 
      reference_list.append(-int((count * (count + 1))/2)) 

     if index < len(first_window) - 2 and first_window[index] == first_window[index + 1]: 
      index += 1 

    return reference_list 

当然,这种算法可以优化,例如,我们可以像避免重复:len(first_window) - 2