基本的Python递归麻烦

时间:2012-09-22 17:31:34

标签: python

我在弄清楚为什么我的代码不起作用时遇到了一些麻烦,并且如果有人能指出我缺少的东西,我会很感激。这是一个基本的算法问题:给定一组不同的排序整数,确定是否存在a [i] = i(例如a [3] = 3)的元素。

我尝试使用print语句调试它,但它只调用FindIndex而不是递归。

以下是代码:

import math

def FindIndex(SetToSearch, beginningIndex, endingIndex):
    """Searches a list of sorted integers to see if there is some a[i] == i

    Keyword Arguments:
    SetToSearch -- a list of disctinct sorted integers 
    beginningIndex -- start point of index to search
    endingIndex -- end point to search """
    # calculate midpoint of set
    midpointIndex = math.ceil((beginningIndex + endingIndex) / 2)
    midpoint = SetToSearch[int(midpointIndex)]
    print "beginningIndex: %s, endingIndex: %s" %(beginningIndex,endingIndex)
    print "midpointIndex: %s, midpoint: %s" % (midpointIndex, midpoint)
    # check whether ending index is greater then beginning index
    if (endingIndex > beginningIndex):
        return "There is no value in this set such that a[i] = i"
    if (endingIndex == beginningIndex):
        if SetToSearch[beginningIndex] == SetToSearch[endingIndex]:
            return "a[%s] is equal to %s" % [beginningIndex, beginningIndex]
    if (midpoint == midpointIndex):
        return "The value at index %d" % midpointIndex
    if (midpoint > midpointIndex):
        print "midpoint > midpointIndex evaluated to true and executed this"
        return FindIndex(SetToSearch, 0, midpointIndex)
    if (midpoint < midpointIndex):
        print "midpoint < midpointIndex evaluated to true and executed this"
        return FindIndex(SetToSearch, midpointIndex + 1, len(SetToSearch) -1)
    else:
        "Something is wrong with your program, because you should never see this!"

sampleSet = [-10, -8, -6, -5, -3, 1, 2, 3, 4, 9 ]
lastIndex = len(sampleSet) - 1

FindIndex(sampleSet,0,lastIndex)

4 个答案:

答案 0 :(得分:1)

问题不在于递归。只是您的第一个条件始终为真:endingIndex始终大于beginningIndex。该条件在没有递归的情况下返回,因此函数在那里结束。

答案 1 :(得分:0)

您可以使用for循环来执行此操作,如:

def find_index_equal_value(set):
    for i in range(0, len(set)):
        val = set[i]
        if(val == i):
           print "Index matches value."

答案 2 :(得分:0)

首先,您必须将return添加到第48行的开头。
其次,将print添加到最后一行的开头。

答案 3 :(得分:0)

首先,如果你看不到发生了什么,那是因为你需要打印返回的字符串:

print FindIndex(sampleSet,0,lastIndex)

现在,如果我运行它,我得到:

beginningIndex: 0, endingIndex: 9
midpointIndex: 4.0, midpoint: -3
There is no value in this set such that a[i] = i

表示此if匹配:

# check whether ending index is greater then beginning index
if (endingIndex > beginningIndex):
    return "There is no value in this set such that a[i] = i"

......好吧,当然它确实 - endingIndex 应该总是大于beginningIndex


为了将来参考,你打印了字符串吗?您是否看到输出线而不理解为什么需要该分支?您是否尝试使用pdb单步执行代码?