我在弄清楚为什么我的代码不起作用时遇到了一些麻烦,如果有人能指出我所缺少的,我将不胜感激。这是一个基本的算法问题:给定一组不同的排序整数,确定是否存在满足 a[i] = i 的元素(例如,a[3] = 3)。
我尝试使用打印语句对其进行调试,但它只调用一次 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)