Python 超出递归限制
Python exceeds recurssion limit
我正在尝试使用分而治之策略开发合并排序算法。但是,在除法部分,我收到一个递归错误,表明我已经超出了递归。这是我得到的:
c = [3,5,4,2,1,6,7]
def mergesort(nums):
if len(nums) == 1:
return
n = len(nums)//2
a = c[:n]
b = c [n:]
mergesort(a)
mergesort(b)
i = 0
j = 0
k = 0
mergesort(c)
这是因为您正在修改全局 c
列表而不是参数 nums
列表(这是您的退出条件)。
c = [3,5,4,2,1,6,7]
def mergesort(nums):
if len(nums) == 1:
return
n = len(nums)//2
a = nums[:n] # Don't use c[:n] here
b = nums[n:] # Don't use c[n:] here
print ('nums: {}\n{}\n{}\n\n'.format(nums, a, b))
mergesort(a)
mergesort(b)
mergesort(c)
我正在尝试使用分而治之策略开发合并排序算法。但是,在除法部分,我收到一个递归错误,表明我已经超出了递归。这是我得到的:
c = [3,5,4,2,1,6,7]
def mergesort(nums):
if len(nums) == 1:
return
n = len(nums)//2
a = c[:n]
b = c [n:]
mergesort(a)
mergesort(b)
i = 0
j = 0
k = 0
mergesort(c)
这是因为您正在修改全局 c
列表而不是参数 nums
列表(这是您的退出条件)。
c = [3,5,4,2,1,6,7]
def mergesort(nums):
if len(nums) == 1:
return
n = len(nums)//2
a = nums[:n] # Don't use c[:n] here
b = nums[n:] # Don't use c[n:] here
print ('nums: {}\n{}\n{}\n\n'.format(nums, a, b))
mergesort(a)
mergesort(b)
mergesort(c)