class index(object):
def __init__(self,low,high,total):
self.low = low
self.high = high
self.total = total
def printing(self):
print "Low:",self.low
print "High:",self.high
print "Total:",self.total
def max_crossing_subarray(A,low,mid,high):
sum, left_sum = 0, -10000000 # Better limit for left_sum
left_max = mid
for i in xrange(mid-1,low-1,-1):
sum += A[i]
if sum > left_sum :
left_sum = sum
left_max = i
sum, right_sum = 0, -10000000 # Better limit for right_sum
right_max = mid
for i in xrange(mid,high):
sum += A[i]
if sum > right_sum:
right_sum = sum
right_max = i
total = left_sum + right_sum
cross_sub = index(left_max,right_max,total)
return cross_sub
def max_subarray(A,low,high):
if low >= 0 and high < len(A):
base = index(low,high,A[low])
if high == low :
return base
else:
mid = ( high + low )/2
left = max_subarray(A,low,mid)
right = max_subarray(A,mid+1,high)
cross = max_crossing_subarray(A,low,mid,high)
if left.total >= right.total and left.total >= cross.total:
return left
elif right.total >= left.total and right.total >= cross.total:
return right
else:
return cross
def main():
print "Enter a sequence:"
A = map(int , raw_input().split())
result = max_subarray(A,0,len(A))
result.printing()
为了确定最大子阵列,我写了上面的代码。 我得到的问题是,在编译时它显示:
我是Python的初学者,我真的很喜欢这里的一些指导。
谢谢。
编辑:
异常的完整回溯日志:
Traceback (most recent call last):
File "main2.py", line 59, in <module>
main()
File "main2.py", line 57, in main
result.printing()
AttributeError: 'NoneType' object has no attribute 'printing'
答案 0 :(得分:0)
编辑:在主要部分中,您将提供max_subarray
函数len(A)
函数,该函数指出A
列表中有多少元素。相反,你应该从中减去一个,因为(我认为)的意图是给出寻找子阵列的范围,因此A[len(A)]
是不正确的。
result = max_subarray(A, 0, len(A) - 1)
此外,我不确定您的算法是否正确,请检查如果要增加序列会发生什么。