Search code examples
pythonfunctionreturnpython-class

class method not returning sorted list in python


class Solution:
    def sortedSquares(self, numbs):
        n = len(numbs)
        for i in range(n):
            numbs[i] = numbs[i] * numbs[i]
        return numbs.sort()
    
sol = Solution()
nums = [-4,-1,0,3,10]
sol.sortedSquares(nums)

Class solution should return sorted list but returning nothing, I check the values of the nums list I got the correct output but I don't know why this method not returning sort list, I tried working around it by changing the variables declaration, but nothing helped.


Solution

  • .sort() returns None

    So, you want to use sorted instead:

    class Solution:
        def sortedSquares(self, numbs):
            n = len(numbs)
            for i in range(n):
                numbs[i] = numbs[i] * numbs[i]
            return sorted(numbs)
        
    sol = Solution()
    nums = [-4,-1,0,3,10]
    sol.sortedSquares(nums)
    

    but if you do want to use .sort() still, just call the .sort() method and then return the numbs:

    class Solution:
        def sortedSquares(self, numbs):
            n = len(numbs)
            for i in range(n):
                numbs[i] = numbs[i] * numbs[I]
            numbs.sort()
            return numbs
            
        
    sol = Solution()
    nums = [-4,-1,0,3,10]
    sol.sortedSquares(nums)
    

    Either way is fine.