[英]Can anyone tell me what's wrong with my Merge Sort in Python?
It's giving me the following errors and I know it has to do with the fact that the left or right array are sometimes None. 它给了我以下错误,我知道这与以下事实有关:左数组或右数组有时为None。 I just don't know why that's the case.
我只是不知道为什么会这样。 The error:
错误:
File "/Users/lezoudali/Documents/Algorithms/sort.py", line 62, in merge
while i < len(left) and j < len(right):
TypeError: object of type 'NoneType' has no len()
My code: 我的代码:
from random import randint
alist = [randint(1,50) for i in range(10)]
def merge(left, right):
i = j = 0
result = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
def mergesort(alist):
if len(alist) == 1:
return alist
mid = len(alist) // 2
left = mergesort(alist[:mid])
right = mergesort(alist[mid:])
return merge(left, right)
print mergesort(alist)
It turns out I was not returning my result from the merge function. 事实证明,我没有从merge函数返回结果。 So the function was return None, which was the problem I was having.
所以函数返回None,这就是我遇到的问题。 Thanks senderle!
谢谢senderle!
def merge(left, right):
i = j = 0
result = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.