我用python编写了一个计数反转程序,并用python27实现了这个程序。我用分而治之的技术实现了alogorithm(合并排序技巧)。我的程序对于大小为upill 100的输入数组运行良好(这是我可以验证的最大值)。 现在,我在大小为50000和100000的输入数组上测试了我的程序,但始终无法得到正确的答案。我已经在下面粘贴了我的代码,请指出任何可能的错误:
f=open('forum.txt')
a=[]
s=1
for line in f:
a.append(line)
def CountInversion(IntegerArray):
_count=0
lc=0
rc=0
RightArray=[]
LeftArray=[]
if len(IntegerArray)>1:
LeftArray,lc=CountInversion(IntegerArray[:len(IntegerArray)/2])
RightArray,rc=CountInversion(IntegerArray[len(IntegerArray)/2:])
elif len(IntegerArray)==1:
return IntegerArray,0
ResultArray=IntegerArray
i=0
l=len(ResultArray)
j,k=0,0
for i in range(0,l):
if j<len(RightArray) and k<len(LeftArray):
if RightArray[j]<LeftArray[k]:
ResultArray[i]=RightArray[j]
j += 1
a=(len(LeftArray)-k)
_count = _count + a
else:
ResultArray[i]=LeftArray[k]
k += 1
elif j<len(RightArray):
ResultArray[i]=RightArray[j]
j += 1
elif k<len(LeftArray):
ResultArray[i]=LeftArray[k]
k += 1
return ResultArray,(_count+lc+rc)
arr,b=CountInversion(a)
print ('end of inversions')
print b
我还运行了J.F.Sebastian在thispost中给出的代码,但是结果是相同的(对于小输入,答案是正确的,但是对于大小为50000或1000000的输入数组则不正确)
这个问题通过将字符串解析为int并填充数组来解决
相关问题 更多 >
编程相关推荐