使用递归但不使用for循环

时间:2017-08-14 07:32:05

标签: python python-3.x recursion

我已经使用递归编写了代码,但后来意识到深度太高而且不适用于更高级别的输入值。它完全没问题。

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 + index:

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。我真的很震惊,我不明白我错过了什么逻辑。任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

仅读取 first_window 变量,并且 index 变量仅递增。不需要递归,一个简单的循环就可以工作。

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