Skip to content

Commit a01b8cc

Browse files
python: add problem 46 and unittest
1 parent cc0ab4a commit a01b8cc

File tree

2 files changed

+44
-8
lines changed

2 files changed

+44
-8
lines changed

Python/solution_41_50.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,38 @@
11
# -*- coding: UTF-8 -*-
22

33
class Solution_41_50:
4+
def permute(self, nums):
5+
"""
6+
problem 46
7+
Given a collection of distinct numbers, return all possible permutations.
8+
9+
For example,
10+
[1,2,3] have the following permutations:
11+
[
12+
[1,2,3],
13+
[1,3,2],
14+
[2,1,3],
15+
[2,3,1],
16+
[3,1,2],
17+
[3,2,1]
18+
]
19+
20+
:type nums: List[int]
21+
:rtype: List[List[int]]
22+
"""
23+
res = [[nums[0]]]
24+
for n in nums[1:]:
25+
old_res = res
26+
res = []
27+
print(old_res)
28+
for l in old_res:
29+
res.extend(list(map(lambda i: l[:i] + [n] + l[i:], range(len(l) + 1))))
30+
return res
31+
432
def groupAnagrams(self, strs):
533
"""
34+
problem 49
35+
636
Given an array of strings, group anagrams together.
737
838
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],

Python/test_solution_41_50.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
from unittest import TestCase
22
from solution_41_50 import Solution_41_50
33

4+
45
# -*- coding: UTF-8 -*-
56
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(['']), [['']])
7+
def setUp(self):
8+
self.sln = Solution_41_50()
9+
10+
def test_permute(self):
11+
a = [1, 2, 3]
12+
b = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
13+
self.assertCountEqual(self.sln.permute(a), b)
14+
15+
def test_groupAnagrams(self):
16+
a = ["eat", "tea", "tan", "ate", "nat", "bat"]
17+
b = [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
18+
self.assertCountEqual(self.sln.groupAnagrams(a), b)
19+
self.assertCountEqual(self.sln.groupAnagrams(['']), [['']])

0 commit comments

Comments
 (0)