Name Error: name 'counting sort' is not defined
Name Error: name 'counting sort' is not defined
我试图实现“糖果数量最多的孩子”代码问题,所以我开始对数组进行排序,但它给了我这个错误,为什么?
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))
当你制作 class 的解决方案时,counting_sort 是这个 class 的一个方法,所以你可以将 self 作为第一个参数传递(在每个 class 方法中).
最后,您可以创建 class 解决方案的对象并从该对象调用方法。您的代码可能如下所示。
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))
我试图实现“糖果数量最多的孩子”代码问题,所以我开始对数组进行排序,但它给了我这个错误,为什么?
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))
当你制作 class 的解决方案时,counting_sort 是这个 class 的一个方法,所以你可以将 self 作为第一个参数传递(在每个 class 方法中).
最后,您可以创建 class 解决方案的对象并从该对象调用方法。您的代码可能如下所示。
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))