java或python中范围的递归max函数

时间:2013-07-17 03:04:30

标签: java python recursion max

我从'思考java,如何像计算机科学家一样思考'这个练习。作者:Allen B Downey:

  

编写一个名为maxInRange的方法,它接受一个整数数组   和一系列索引(lowIndexhighIndex),并找到   数组中的最大值,仅考虑之间的元素   lowIndexhighIndex,包括两端。

     

此方法应该是递归的。如果范围的长度为1,即   如果lowIndex == highIndex,我们立即知道唯一的元素   在范围内必须是最大的。这就是基本情况。

     

如果范围中有多个元素,我们可以破坏数组   分成两块,找到每块中的最大值,然后找到   最大值的最大值。

我在python中得出了一个接近但非常不准确的答案:

cycles=0

def max_in_range(lst,low,high):

    '''

    Could not be able to make it work correctly

    '''



    global cycles

    cycles+=1

    if low==high:

        #print "Cycles: ",cycles

        return lst

    else:

        max_left=max_in_range(lst[low:len(lst)/2+1],low+1,high)

        max_right=max_in_range(lst[len(lst)/2:len(lst)],low+1,high)

        return max_right if max_right>max_left else max_left



lst=[112,32,45,71238,9999,45,12,6,3]   # always Returns the mid element.

print max_in_range(lst,0,10)



def max(lst):

    global cycles

    cycles+=1

    if len(lst)==1:

        print "Cycles: ",cycles

        return lst[0]

    else:

        m=max(lst[1:])

        return m if m> lst[0] else lst[0]



print max(lst)

与问题所要求的相比,max函数很容易,即函数
是递归的,采取两个限制并在运行时拆分列表。 max_in_range函数始终返回数组中的mid元素,即9999

我需要一些关于如何满足问题要求的指示。在Java或Python或其他类似C语言。

2 个答案:

答案 0 :(得分:2)

请参阅代码中的注释。

def max_in_range(lst, low, high):
    # If the length of the range is 1, the sole element in the range must be the maximum.
    if low == high:
        return lst[low]

    # break the array into two pieces, lst[low:low+1] / lst[low+1:high+1],
    # find the maximum in each of the pieces
    piece1_max = lst[low]
    piece2_max = max_in_range(lst, low + 1, high)

    # find the maximum of the maxima
    if piece1_max > piece2_max:
        return piece1_max
    else:
        return piece2_max

lst = [112,32,45,71238,9999,45,12,6,3]
print max_in_range(lst, 0, len(lst) - 1)

答案 1 :(得分:0)

您需要将通话更改为:

print max_in_range(lst,0,len(lst))

这样你就不会像你的例子那样溢出数组。

但其余的应该是这样的:

split = low + ((high - low) / 2)

max_left  = max_in_range(lst, low, split - 1)
max_right = max_in_range(lst, split, high)