class Solution:
def topR(self, num,b)
To run a class, it is usually like:
aa=Solution()
kk=aa.topR(x1,x2)
And the self can not be omitted. Otherwise, we will get an error.
Here is an example, top k frequentest number in a list:
import collections
import operator
class Solution:
def topN(self, num,k):
b=collections.defaultdict(int)
for i in num:
b[i]+=1
sorted_x = sorted(b.items(), key=operator.itemgetter(1),reverse=True)
return sorted_x[:k]
aa=Solution()
print aa.topN([1,1,1,2,3,3,3,5,5,5,5,9,9,9,9,9,9,9,9],2)
Results:
[(9, 8), (5, 4)]
No comments:
Post a Comment