Skip to content

Commit d1436dc

Browse files
authored
Merge pull request #16 from nickolasteixeira/nick
logic change for permutations - chapter 1
2 parents b5ca28c + 048ef4d commit d1436dc

File tree

1 file changed

+27
-4
lines changed
  • Python/chapter01/1.4 - PalinPerm

1 file changed

+27
-4
lines changed

Python/chapter01/1.4 - PalinPerm/Nick4.py

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
'''
77

88
import unittest
9-
9+
import collections
1010

1111
def palperm(string):
1212
'''
@@ -15,17 +15,30 @@ def palperm(string):
1515
string (str): a string to check for all palindrome permutations
1616
'''
1717
table = {}
18-
count = 0
1918
for letter in string.lower().replace(" ", ""):
2019
table[letter] = table.get(letter, 0) + 1
2120

21+
count = 0
2222
for key in table:
23-
if count > 1:
24-
return False
2523
if table[key] % 2 == 1:
2624
count += 1
25+
if count > 1:
26+
return False
2727
return True
2828

29+
def palperm2(string):
30+
letter_frequencies = collections.defaultdict(int)
31+
for letter in string.lower().replace(' ', ''):
32+
letter_frequencies[letter] += 1
33+
34+
odd_frequency_count = 0
35+
for frequency in letter_frequencies.values():
36+
if frequency % 2 == 0:
37+
continue
38+
odd_frequency_count += 1
39+
if odd_frequency_count > 1:
40+
return False
41+
return True
2942

3043
class Test(unittest.TestCase):
3144
def test1(self):
@@ -38,5 +51,15 @@ def test1(self):
3851
self.assertTrue(palperm(input_string3))
3952
self.assertTrue(palperm(input_string4))
4053

54+
def test2(self):
55+
input_string ="Tact Coa"
56+
input_string2 ="nick"
57+
input_string3 ="saippuakivikauppias"
58+
input_string4 = "iasppaukivikauppias"
59+
self.assertTrue(palperm2(input_string))
60+
self.assertFalse(palperm2(input_string2))
61+
self.assertTrue(palperm2(input_string3))
62+
self.assertTrue(palperm2(input_string4))
63+
4164
if __name__ == '__main__':
4265
unittest.main()

0 commit comments

Comments
 (0)