【问题标题】:Fixing Gap in Knowledge about recursion: base conditions and state修复关于递归的知识差距:基本条件和状态
【发布时间】:2017-08-19 04:22:26
【问题描述】:

我在递归方面存在知识差距。我知道基本情况应该终止递归,但我很难选择正确的。

此外,我在理解如何在不更新方法签名的情况下管理状态方面存在问题。

largest adjacent element products的问题为例。我对分而治之的理解是:

1) divide the problem into smaller problems:
    1.1) create a left array of the first two elements
    1.2) create a right array by removing the first element
2) conquer by recursion:
    2.1) repeat the function on the right array
    2.2) choose a good base case to terminate
3) combine the solution
    3.1) this is where things get tricky!? 
    3.2) for the task of multiplication, how do I persist the result
    after each recursion when each new call will re-instantiate the
    result list

下面是这种知识差距的一个具体示例:我选择的base case 是当列表中的元素少于两个时,则返回0。当然,当两个元素的乘积为less than 0 时,except 有效。

为基本情况返回None 是状态问题,因为在python3 None 和int 比较中会引发错误。

TypeError: '>=' not supported between instances of 'int' and 'NoneType'

完整代码如下

def multiply(inputArray):
    m = inputArray[0] * inputArray[1]
    return m

def adjacentElementsProduct(inputArray):
    # [3, 6, -2, -5, 7, 3]
    if len(inputArray) <= 1:
        # return 0
        return None

    left = inputArray[:2]
    right = inputArray[1:]
    result = []

    result.append(adjacentElementsProduct(right))
    m = multiply(left)

    print(result, left, m)

    if len(result) == 0:
        result.append(m)
    else:
        if m >= result[0]:
            result.insert(0, m)

    return result[0]

【问题讨论】:

    标签: python-3.x recursion divide-and-conquer


    【解决方案1】:

    似乎您的主要问题是如何组合解决方案。在每一次迭代中,你需要组合的是左数组和右数组的结果。

    如何保持结果?

    只返回左结果和右结果的最大值。

    def adjacentElementsProduct(inputArray):
        # [3, 6, -2, -5, 7, 3]
        if len(inputArray) <= 1:
            return None
    
        left = inputArray[:2]
        right = inputArray[1:]
    
        m = multiply(left)
    
        result = adjacentElementsProduct(right)
    
        # combine solutions
        if result is None:
            return m
        else:
            return max(m, result)
    

    测试用例:

    print(adjacentElementsProduct([3]))
    None
    print(adjacentElementsProduct([3,6]))
    18
    print(adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
    21
    

    【讨论】:

    • python 没有任何附加信息。有一个insert(0, m)。解决方案也应该返回一个整数。
    • @SamHammamy 修复它。确切的结果应该是什么?我不明白adjacent element products
    • 输出应该是21:最大元素积
    • @SamHammamy 所以你想要的是最大相邻元素的产品。你没有提到那个。
    • 您仍在返回一个列表,而不是一个整数。我为否决票道歉,我更正并投了赞成票,但我不能接受作为正确答案,因为它仍在返回一个列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多