ezoic

Monday, January 30, 2017

Generally a python class structure

When we study a python class structure, we will have __init__, self, etc. But in general, when we write a python class, it is usually like:

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

looking for a man

 I am a mid aged woman.  I was born in 1980. I do not have any kid. no complicated  dating before . I am looking for a man here for marriage...