RuntimeError:Python中超出了最大递归深度

时间:2015-05-04 14:53:29

标签: python recursion binary-search

#Recursive BinaryChop
def recursiveBinaryChop( value, elementList, min, max ):
    if len( elementList ) == 0:
        return -1
    if max <= min:
        if ( max == min and elementList[min] == value ):
            return min
        else:
            return -1
    else:
        midPointOfList = ( min + max ) / 2

        if elementList[midPointOfList] > value:
            max = --midPointOfList
            return recursiveBinaryChop( value, elementList, min, max )
        elif elementList[midPointOfList] < value:
            min = ++midPointOfList
            return recursiveBinaryChop( value, elementList, min, max )
        else:
            return midPointOfList

#Recursive BinaryChop Test Cases
assert recursiveBinaryChop(3, [], 0, 0) == -1
assert recursiveBinaryChop(3, [1], 0, 0) == -1
assert recursiveBinaryChop(1, [1], 0, 0) == 0
assert recursiveBinaryChop(1, [1, 3, 5], 0, 2) == 0
assert recursiveBinaryChop(3, [1, 3, 5], 0, 2) == 1
assert recursiveBinaryChop(5, [1, 3, 5], 0, 2) == 2
assert recursiveBinaryChop(0, [1, 3, 5], 0, 2) == -1
assert recursiveBinaryChop(2, [1, 3, 5], 0, 2) == -1
assert recursiveBinaryChop(4, [1, 3, 5], 0, 2) == -1
assert recursiveBinaryChop(6, [1, 3, 5], 0, 2) == -1
assert recursiveBinaryChop(1, [1, 3, 5, 7], 0, 3) == 0
assert recursiveBinaryChop(3, [1, 3, 5, 7], 0, 3) == 1
assert recursiveBinaryChop(5, [1, 3, 5, 7], 0, 3) == 2
assert recursiveBinaryChop(7, [1, 3, 5, 7], 0, 3) == 3
assert recursiveBinaryChop(0, [1, 3, 5, 7], 0, 3) == -1
assert recursiveBinaryChop(2, [1, 3, 5, 7], 0, 3) == -1
assert recursiveBinaryChop(4, [1, 3, 5, 7], 0, 3) == -1
assert recursiveBinaryChop(6, [1, 3, 5, 7], 0, 3) == -1
assert recursiveBinaryChop(8, [1, 3, 5, 7], 0, 3) == -1

我得到这个简单代码的运行时错误,我已经尝试过搜索但是所有答案似乎建议设置递归限制,但我没有看到我的测试输入发生了这种情况。我不确定我的算法是错误的还是有一些逻辑错误。我在C++中使用相同的算法。

请帮忙。

2 个答案:

答案 0 :(得分:6)

    if elementList[midPointOfList] > value:
        max = --midPointOfList
        return recursiveBinaryChop( value, elementList, min, max )
    elif elementList[midPointOfList] < value:
        min = ++midPointOfList
        return recursiveBinaryChop( value, elementList, min, max )

Python没有 - 或++运算符。如果您尝试递减和递增,请尝试“-1”和“+1”。

    if elementList[midPointOfList] > value:
        max = midPointOfList - 1
        return recursiveBinaryChop( value, elementList, min, max )
    elif elementList[midPointOfList] < value:
        min = midPointOfList + 1
        return recursiveBinaryChop( value, elementList, min, max )

(这与C ++的--++的行为不完全相同,因为midPointOfList的值保持不变,但在这种情况下这似乎并不重要; midPointOfList无论如何都不会被引用。

答案 1 :(得分:5)

这两行不符合您的想法:

max = --midPointOfList
min = ++midPointOfList

Python没有这种类型的增量运算符,但它们解析并成功执行。

++i+(+i)--i解析为-(-i)。两者都保持i不变并且实际上是

max = midPointOfList
min = midPointOfList