-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup_anagrams.py
More file actions
30 lines (21 loc) · 763 Bytes
/
group_anagrams.py
File metadata and controls
30 lines (21 loc) · 763 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
''' Write a function to group anagrams together from a given list of strings .
Input : ['cat', 'dog', 'tac', 'god', 'act']
Output : [['act', 'cat', 'tac'], ['dog', 'god']]
Input : ['abcd','dcba','lll']
Output : [['abcd', 'dcba'], ['lll']]
Input : ['a']
Output : [['a']]
Input : ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
Output : [['ate', 'eat', 'tea'], ['nat', 'tan'], ['bat']]
'''
from collections import defaultdict
def group_anagrams(strs):
anagrams = defaultdict(list)
for i in strs:
sorted_string = ''.join(sorted(i))
print('sorted : ',sorted_string)
anagrams[sorted_string].append(i)
print(anagrams)
return list(anagrams.values())
l = ['tea', 'eat', 'tan', 'ate', 'nat', 'bat']
print(group_anagrams(l))