0

Totally new to Python OOP. I am trying to write a code to separate anagrams (https://en.wikipedia.org/wiki/Anagram) in a list. The original question from Leetcode is here (https://leetcode.com/problems/anagrams/) For example:

strs=["eat", "tea", "tan", "ate", "nat", "bat"]

It should return:

[['eat', 'tea','tan','ate','nat'], ['bat']]

I see some discussion codes like (https://leetcode.com/discuss/51190/1-line-ruby-python-for-updated-problem):

def groupAnagrams(self, strs):
    groups = collections.defaultdict(list)
    for s in strs:
        groups[tuple(sorted(s))].append(s)
    return map(sorted, groups.values())

Or (https://leetcode.com/discuss/83032/without-sorting-each-string-use-hash-instead-concise-python)

def groupAnagrams(self, strs):
    dic = collections.defaultdict(list)
    for str in strs:
        dic[reduce(operator.mul, map(hash, str), 1)].append(str)
    return map(sorted, dic.values())

The question is: how can I make this class/function runs to take the list "strs" as an input and output the desired list?

groupAnagrams(self,list1)

NameError: name 'self' is not defined
Chubaka
  • 2,933
  • 7
  • 43
  • 58

1 Answers1

0

Call class then we will use the method:

class A(object):
     some_method = groupAnagrams

a = A()
print a.some_method(list1)

this will give us:

[['bat'], ['ate', 'eat', 'tea'], ['nat', 'tan']]
Chubaka
  • 2,933
  • 7
  • 43
  • 58
  • Are you sure you have to use OOP approach here? Why don't you want to define `groupAnagrams` outside the class and leave the `self` parameter? – awesoon Mar 13 '16 at 04:26
  • I don't think OOP here is necessary, but all the leetcode discussion scripts are in OOP, which kinda annoy me. Really no need for OOP in such a short script! – Chubaka Mar 13 '16 at 06:51