python - Getting "object of type 'NoneType' has no len()" during implementation of mergeSort
问题描述
I'm trying to implement mergeSort in python but getting Type error.
I tried debugging my code but didn't got any success.
def merge(L, R):
(C, m, n) = ([], len(L), len(R))
(i,j) = (0,0)
while i+j < m+n:
if i == m: # Case 1 -> List A is empty
C.append(R[j])
j += 1
elif j == n: # Case 2 -> List B is empty
C.append(L[i])
i += 1
elif L[i] <= R[j]: # Case 3 -> Head of A is smaller
C.append(L[i])
i += 1
elif L[i] > R[j]:
C.append(R[j])
j += 1
print(C)
def mergeSort(A, left, right):
if right - left <= 1: # Base Case
return(A[left:right])
if right - left > 1: # Recurive call
mid = (left+right)//2
L = mergeSort(A, left, mid)
R = mergeSort(A, mid, right)
return(merge(L, R))
If anyone know what I'm doing wrong, please guide me to the right way.
解决方案
merge
必须返回C
,而不是打印。
def merge(L, R):
(C, m, n) = ([], len(L), len(R))
(i,j) = (0,0)
while i+j < m+n:
if i == m: # Case 1 -> List A is empty
C.append(R[j])
j += 1
elif j == n: # Case 2 -> List B is empty
C.append(L[i])
i += 1
elif L[i] <= R[j]: # Case 3 -> Head of A is smaller
C.append(L[i])
i += 1
elif L[i] > R[j]:
C.append(R[j])
j += 1
return C
推荐阅读
- java - 短信通知默认声音的uri
- react-native - Android:react-native-image-picker manifest.xml 文件路径无效
- file - 如何为应用程序工作会话设置一次文件中的常量
- regex - 通过正则表达式识别句子中的单词
- c++ - 三元运算符为什么以及何时返回左值?
- python - 使用python计算肽单同位素
- c# - 尝试不每秒创建新文件,但如果文件限制超过则使用 log4net 创建新文件
- windows - 使用不带方括号的 dir /D 命令作为输出
- haskell - Haskell 中使用 List Monad 的下推自动机
- java - 如何分配多维输出缓冲区来提供 Android Tflite 的interpreter.run()?