[英]Error returned from a Merge Sort function in Python
I have tried to write a Merge Sort function as you can see below.我尝试编写一个合并排序函数,如下所示。 But when I try to test it I receive an error:但是当我尝试测试它时,我收到一个错误:
the name mergesort is not defined
Can anyone point out the cause for this error?谁能指出这个错误的原因?
def merge(self,a,b):
sorted_list=[]
while len(a)!=0 and len(b)!=0:
if a[0].get_type()<b[0].get_type():
sorted_list.append(a[0])
a.remove(a[0])
else:
sorted_list.append(b[0])
b.remove(b[0])
if len(a)==0:
sorted_list+=b
else:
sorted_list+=a
return sorted_list
def mergesort(self,lis):
if len(lis) == 0 or len(lis) == 1:
return lis
else:
middle = len(lis)// 2
a = mergesort(lis[middle:]) #in pycharm the next 3 lines are with red underlined
b = mergesort(lis[middle:])
return merge(a,b)
The fact that self
is one of the parameters to these methods means that they're most likely part of a class (one you've omitted from your post). self
是这些方法的参数之一这一事实意味着它们很可能是类的一部分(您在帖子中省略了一个类)。
If that's correct, you need to invoke using self.mergesort(l)
, where l
is a list.如果这是正确的,您需要使用self.mergesort(l)
进行调用,其中l
是一个列表。
As a pre-emptive measure against the next error you'll discover, you need to replace return merge(a, b)
with return self.merge(a, b)
for similar reasons.作为针对您将发现的下一个错误的先发制人的措施return self.merge(a, b)
出于类似的原因,您需要将return merge(a, b)
替换为return self.merge(a, b)
。
Finally, I have to ask why you're defining all of these functions as methods of a class.最后,我不得不问为什么你将所有这些函数定义为一个类的方法。 They don't seem to rely on any shared data.他们似乎不依赖任何共享数据。 Are you confident that they wouldn't be more appropriately declared at the module scope?您是否确信在模块范围内声明它们不会更合适?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.