-
Notifications
You must be signed in to change notification settings - Fork 19
/
1.4-Palindrome_Permutation.py
84 lines (68 loc) · 1.91 KB
/
1.4-Palindrome_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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# CTCI 1.4
# Palindrome Permutation
import unittest
from collections import Counter
# My Solution
def palindrome_permutation(string):
one = False
if len(string) % 2 == 0:
even = True
else:
even = False
counter = Counter()
# Increment counter for each chat
for c in string:
counter[c] += 1
for c in string:
if counter[c] % 2 != 0:
if one or even:
return False
one = True
return True
#-------------------------------------------------------------------------------
# CTCI Solution
def pal_perm(phrase):
'''function checks if a string is a permutation of a palindrome or not'''
table = [0 for _ in range(ord('z') - ord('a') + 1)]
countodd = 0
for c in phrase:
x = char_number(c)
if x != -1:
table[x] += 1
if table[x] % 2:
countodd += 1
else:
countodd -= 1
return countodd <= 1
def char_number(c):
a = ord('a')
z = ord('z')
A = ord('A')
Z = ord('Z')
val = ord(c)
if a <= val <= z:
return val - a
elif A <= val <= Z:
return val - A
return -1
#-------------------------------------------------------------------------------
#Testing
class Test(unittest.TestCase):
'''Test Cases'''
''' I disagree with these palindromes '''
data = [
('Tact Coa', True),
('jhsabckuj ahjsbckj', True),
('Able was I ere I saw Elba', True),
('So patient a nurse to nurse a patient so', False),
('Random Words', False),
('Not a Palindrome', False),
('no x in nixon', True),
('azAZ', True)]
def test_pal_perm(self):
for [test_string, expected] in self.data:
actual = pal_perm(test_string)
print(actual)
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()