Last active
August 7, 2018 07:29
-
-
Save ffuentese/fec05be86bb5c780fe772387529915ae to your computer and use it in GitHub Desktop.
Palindrome unicode https://repl.it/@ffuentes/SnappyLoyalPi-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
String.translate had a little issue with a long dash (—) that I casually found in a Russian palindrome. It worked!