pythonsortingcounting-sort

Name Error: name 'counting sort' is not defined


i trying to implement 'Kids With the Greatest Number of Candies'leet'code problem so i started with sorting the array but it gives me this error why?

class Solution:
    def counting_sort(arr):
        n = len(arr)
        k = max(arr) + 1
        position = [0] * k
        for v in arr:
            position[v] += 1

        s = 0
        for i in range(0, k):
            temp = position[i]
            position[i] = s
            s += temp
        result = [None] * n
        for v in arr:
            result[position[v]] = v
            position[v] += 1
        return result
    def kidsWithCandies(candies, extraCandies):
        candies=counting_sort(candies)
        main_arr=[True]*len(candies)-1
        i=0
        biggest=max(candies)
        while(candies[i]+extraCandies<biggest and i<len(candies)):
            main_arr[i]=False
            i+=1
        return main_arr
    print(kidsWithCandies([2,3,5,1,3],3))

Solution

  • As you're making class of Solution and counting_sort is a method of this class so you can pass self as first parameter (in every class method).

    in the end you can make object of class Solution and call method from that object. Your code may look like this.

    class Solution:
        def counting_sort(self, arr):
            n = len(arr)
            k = max(arr) + 1
            position = [0] * k
            for v in arr:
                position[v] += 1
    
            s = 0
            for i in range(0, k):
                temp = position[i]
                position[i] = s
                s += temp
            result = [None] * n
            for v in arr:
                result[position[v]] = v
                position[v] += 1
            return result
    
        def kidsWithCandies(self,candies, extraCandies):
            candies=self.counting_sort(candies)
            main_arr=[True]*len(candies)-1
            i=0
            biggest=max(candies)
            while(candies[i]+extraCandies<biggest and i<len(candies)):
                main_arr[i]=False
                i+=1
            return main_arr
    
    soln = Solution()
    print(soln.kidsWithCandies([2,3,5,1,3],3))