Skip to content

Commit 6c4b3c2

Browse files
python: add problem 49 and test function
1 parent 09e63c4 commit 6c4b3c2

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Python/solution_41_50.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# -*- coding: UTF-8 -*-
2+
3+
class Solution_41_50:
4+
def groupAnagrams(self, strs):
5+
"""
6+
Given an array of strings, group anagrams together.
7+
8+
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
9+
Return:
10+
11+
[
12+
["ate", "eat","tea"],
13+
["nat","tan"],
14+
["bat"]
15+
]
16+
:type strs: List[str]
17+
:rtype: List[List[str]]
18+
"""
19+
word_maps = {}
20+
if len(strs) <= 1:
21+
return [strs]
22+
23+
word_maps[str(sorted(strs[0]))] = [strs[0]]
24+
for s in strs[1:]:
25+
sign = str(sorted(s))
26+
if sign not in word_maps:
27+
word_maps[sign] = [s]
28+
else:
29+
word_maps[sign].append(s)
30+
31+
return word_maps.values()

Python/test_solution_41_50.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from unittest import TestCase
2+
from solution_41_50 import Solution_41_50
3+
4+
# -*- coding: UTF-8 -*-
5+
class TestSolution_41_50(TestCase):
6+
def setUp(self):
7+
self.sln = Solution_41_50()
8+
9+
def test_groupAnagrams(self):
10+
a = ["eat", "tea", "tan", "ate", "nat", "bat"]
11+
b = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
12+
self.assertEqual(self.sln.groupAnagrams(a),b)
13+
self.assertEqual(self.sln.groupAnagrams(['']), [['']])

0 commit comments

Comments
 (0)