简体   繁体   English

python合并排序实现错误:超出最大递归深度

[英]python merge sort implementation error: maximum recursion depth exceeded

Here is a simple merge sort algorithm I tried to implement in python.这是我尝试在 python 中实现的一个简单的合并排序算法。 I tried to do this without using left and right parameters which are found elsewhere, only using slices.我尝试在不使用其他地方找到的左右参数的情况下执行此操作,仅使用切片。

from math import floor


def merge(A, B):
    """Mearges the two sorted lists A and B"""
    merged = []
    i, j = 0, 0
    while i < len(A) and j < len(B):
        if A[i] <= B[j]:
            merged.append(A[i])
            i += 1
        else:
            merged.append(B[j])
            j += 1
    
    if j == len(B):
        merged.extend(A[i:])
    elif i == len(A):
        merged.extend(B[j:])
    
    return merged

def merge_sort(A):
    if len(A) == 1:
        return A
    
    m = floor(len(A) / 2)
    half1 = A[0:m]    
    half2 = A[m:]
    A = merge_sort(half1)
    B = merge_sort(half2)
    R = merge(A, B)
    return R



def main():
    C = [6, 7, 2]
    print(merge_sort(C))
    exit()

if __name__ == "__main__":
    main()

And it worked fine.它工作得很好。 But when I tried但是当我尝试

A = merge_sort(A[0:m])
B = merge_sort(A[m:])

instead of using the variables half1 and half2 in merge_sort function, I got this:我没有在merge_sort函数中使用变量half1half2 ,而是得到了这个:

Traceback (most recent call last):
  File "/home/aayush/PyProgs/mrg_sort.py", line 44, in <module>
    main()
  File "/home/aayush/PyProgs/mrg_sort.py", line 40, in main
    print(merge_sort(C))
  File "/home/aayush/PyProgs/mrg_sort.py", line 32, in merge_sort
    B = merge_sort(A[m:])
  File "/home/aayush/PyProgs/mrg_sort.py", line 31, in merge_sort
    A = merge_sort(A[0:m])
  File "/home/aayush/PyProgs/mrg_sort.py", line 31, in merge_sort
    A = merge_sort(A[0:m])
  File "/home/aayush/PyProgs/mrg_sort.py", line 31, in merge_sort
    A = merge_sort(A[0:m])
  [Previous line repeated 993 more times]
  File "/home/aayush/PyProgs/mrg_sort.py", line 25, in merge_sort
    if len(A) == 1:
RecursionError: maximum recursion depth exceeded while calling a Python object

Please tell me what I have done wrong.请告诉我我做错了什么。

you just need to keep check of variable naming since here A is updated and you are using that list data not the orignal one您只需要检查变量命名,因为这里 A 已更新,并且您使用的是该列表数据而不是原始数据

def merge_sort(A):
    if len(A) == 1:
        return A
    
    m = floor(len(A) / 2)
    c = merge_sort(A[0:m])
    B = merge_sort(A[m:])
    R = merge(c, B)
    return R

Have you try with smaller data ?您是否尝试使用较小的数据?

Try :尝试 :

import sys sys.setrecursionlimit(10000)导入 sys sys.setrecursionlimit(10000)

Then retry If algorithm not ended, you have an infinite loop然后重试如果算法没有结束,你有一个无限循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM