2014-10-29 57 views
0

它給了我以下錯誤,我知道它與左或右數組有時是無關的事實。我只是不知道爲什麼是這樣。錯誤:任何人都可以告訴我我的合併排序在Python中出了什麼問題?

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() 

我的代碼:

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) 
+2

你的'merge'函數沒有返回任何東西。您將數據從'left'和'right'保存到'result',但沒有'return'語句,'merge'只返回'None'。所以'return merge(left,right)'也返回'None'。 – senderle 2014-10-29 17:24:16

+0

ahhhhhh是的,謝謝先生。 :) – 2014-10-29 17:31:29

回答

1

原來我不是從合併功能回到我的結果。所以函數返回None,這是我遇到的問題。感謝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 
相關問題