Python合并算法

标签 python algorithm merge mergesort

这似乎现在有效...欢迎公开批评。 Ty tsroten。

debug = 1
#List to be merged
A=[1,2,3,4,5,6,1,2,3,4,5,6,7]

#Artificial variables from calling function
p=0
r=len(A)
q=int(((p+r)/2)-1)

#List to append merged values
B=[]

#End of list
end=len(A)

if debug:
    print ('Mid: %d\n' % (q))
    print ('End: %d' % (end))

#Left and Right lists with sentinels
L=A[:q+1]
R=A[q+1:]
L.append(None)
R.append(None)

#Init counters
i=k=j=l=0

if debug:
    print ('A:%s' %(A))
    print ('\n')
    print ('L:%s' %(L))
    print ('R:%s' %(R))
    print ('\n')

#Merge Left and Right lists
for k in A:
    if debug:
        print ('Iteration:%d' % (l))
        l+=1
        print ('i=%d, j=%d' % (i, j))
        print ('B:%s' %(B))
        print ('\n')
    if L[i] is not None and L[i]<=R[j]:
        B.append(L[i])
        i+=1
    else:
        B.append(R[j])
        j+=1

print ('Result:',B)

我正在尝试用 Python 编写合并算法,但我一直遇到这个错误。

Traceback (most recent call last):
  File "C:/Python34/Scripts/mergeSort.py", line 19, in <module>
    if L[i]<=R[j] and i<mid:
IndexError: list index out of range

我看过其他算法,但它们似乎没有同样的问题。请帮忙。

A=[2,4,5,7,1,3,7,8,9]  
B=[]


end=len(A)  
mid=int(end/2)

L=A[:mid]  
R=A[mid+1:]

i=k=j=0

for k in A:  
    if L[i]<=R[j] and i<mid:  
        B.append(L[i])  
        i+=1  
    elif j<end:  
        B.append(R[j])  
        j+=1  

print (B)

最佳答案

您的 for 循环遍历 A 中的所有项目,它比 LR 长。因此,在某些时候,ij 变得大于 LR 的长度。此时,引用 L[i]R[j] 会引发 IndexError

关于Python合并算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31486851/

相关文章:

c# - 合并具有嵌套类的同一类的两个对象

python - 如果存储的数据为十六进制并以str形式存储,如何转换为十六进制

python - 将数据帧转换为字典,如图所示

python - PyOpenCL vs Clyther vs 纯 OpenCL 和 C99 : what's the best for novice?

python - Python Bug 中的合并排序

mysql - 如何在mysql中合并同一列标题下的两列

python - cs50 pset7包含语法

algorithm - 来自有序和级别顺序遍历的二叉树?

algorithm - 什么是特征值和展开式?

r - 一种将不同长度的命名向量合并到 R 中的数据框(将名称信息保留为列名)的快速方法