-
Notifications
You must be signed in to change notification settings - Fork 19
/
1.2-Check_Permutation.py
57 lines (48 loc) · 1.31 KB
/
1.2-Check_Permutation.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# CTCI 1.2
# Check Permutation
import unittest
from collections import Counter
# My Solution
def check_permutation(str1, str2):
if len(str1) != len(str2):
return False
sorted1 = sorted(str1)
sorted2 = sorted(str2)
return sorted1 == sorted2
#-------------------------------------------------------------------------------
# CTCI Solution
def check_permutation2(str1, str2):
if len(str1) != len(str2):
return False
counter = Counter()
for c in str1:
counter[c] += 1
for c in str2:
if counter[c] == 0:
return False
counter[c] -= 1
return True
#-------------------------------------------------------------------------------
#Testing
class Test(unittest.TestCase):
dataT = (
('abcd', 'bacd'),
('3563476', '7334566'),
('wef34f', 'wffe34'),
)
dataF = (
('abcd', 'd2cba'),
('2354', '1234'),
('dcw4f', 'dcw5f'),
)
def test_cp(self):
# true check
for test_strings in self.dataT:
result = check_permutation(*test_strings)
self.assertTrue(result)
# false check
for test_strings in self.dataF:
result = check_permutation(*test_strings)
self.assertFalse(result)
if __name__ == "__main__":
unittest.main()