【发布时间】: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