Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

python - sort() returns None

Code:

import math
import time
import random
class SortClass(object):
    def sort1(self, l):
        if len(l)==1:
            return l
        elif len(l)==2:
            if l[0]<l[1]:
                return l
            else:
                return l[::-1]
        else:
            pivot=math.floor(len(l)/2)
            a=l[pivot:]
            b=l[:pivot]
            a2=self.sort1(a)
            b2=self.sort1(b)
            if a2==None or b2==None:
                a2=[]
                b2=[]
            return (a2+b2).sort()
        return []
Sort=SortClass()
x=[20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
print(Sort.sort1(x))

The code outputs None even though it should return an empty list in two cases:

return []

and

a2=self.mergeSort(a)
b2=self.mergeSort(b)
if a2==None or b2==None:
    a2=[]
    b2=[]
return (a2+b2).sort()

Details: The code is for a list sorting module I am making for python practice (I am relatively new at python). sort1 is a modified mergesort.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

list.sort returns None (sorts in-place):

>>> [].sort() is None
True

You're using it here:

return (a2+b2).sort()

Use sorted to sort to a new list and not in-place:

return sorted(a2+b2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...