Skip to content

Instantly share code, notes, and snippets.

@ffuentese
Last active August 7, 2018 07:29
Show Gist options
  • Save ffuentese/fec05be86bb5c780fe772387529915ae to your computer and use it in GitHub Desktop.
Save ffuentese/fec05be86bb5c780fe772387529915ae to your computer and use it in GitHub Desktop.
import unittest
import palindrome
class TestNormalize(unittest.TestCase):
def test_normalize_russian(self):
str = "Кит на мо́ре — рома́нтик"
rstr = "Кит на море — романтик"
self.assertEqual(rstr, palindrome.normalize(str))
def test_normalize_spanish(self):
str = "Allí ves Sevilla."
rstr = "Alli ves Sevilla."
self.assertEqual(rstr, palindrome.normalize(str))
class TestPalindrome(unittest.TestCase):
def test_english_palindrome(self):
str = "\"Stop!\" nine myriad murmur. \"Put up rum, rum, dairymen, in pots.\""
self.assertTrue(palindrome.palindrome(str))
def test_spanish_palindrome(self):
str = "Allí ves Sevilla."
self.assertTrue(palindrome.palindrome(str))
def test_spanish_n(self):
str = "Aña."
self.assertTrue(palindrome.palindrome(str))
def test_russian_palindrome(self):
str = "Кит на мо́ре — рома́нтик"
self.assertTrue(palindrome.palindrome(str))
def test_another_russian(self):
str = "Мини́стр отли́чно ко́нчил торт си́ним"
self.assertTrue(palindrome.palindrome(str))
unittest.main()
import unicodedata
import re
def reverse_string(str):
# reverses the phrase
return ''.join(reversed(str))
def clean(str):
# helps ignoring punctuation as we check palindrom phrases
#translator=str.maketrans('','',string.punctuation)
#return str.translate(translator)
return re.sub(r'[^\w\s]','', str, 0, re.UNICODE)
def normalize(str):
""" removes accents (if present) from a string """
nfkd_form = unicodedata.normalize('NFKD', str)
text = u"".join([c for c in nfkd_form if not unicodedata.combining(c)])
return text
def palindrome(str):
""" Returns true if the string is a palindrome """
reverso = reverse_string(clean(str.strip())).replace(" ", "").lower()
reverso = normalize(reverso)
original = clean(str.strip()).replace(" ", "").lower()
original = normalize(original)
return original == reverso
@ffuentese
Copy link
Author

String.translate had a little issue with a long dash (—) that I casually found in a Russian palindrome. It worked!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment