Skip to content

Instantly share code, notes, and snippets.

@Ropes
Created May 9, 2014 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ropes/4430e3b9cef8b1ee562d to your computer and use it in GitHub Desktop.
Save Ropes/4430e3b9cef8b1ee562d to your computer and use it in GitHub Desktop.
Palindrome Check
from __future__ import print_function, unicode_literals
def iter_palindrome(string):
'''Memory efficient but unelegant iterative solution.
Starting at each end of the string comapre characters until the center
is reached or iterators overlap if it's semetric
'''
print(string)
i = 0
j = len(string) - 1
mid = j/float(2)
for x in range(i, j):
print('{}:{} {} {}'.format(i, j, string[i], string[j]))
if string[i] == string[j]:
i += 1
j -= 1
elif i == mid and j == mid:
return True
else:
return False
return True
def rec_palindrome(string):
'''Elegant recursive solution which compares first and last characters
and recurses over the internal section of the string.
'''
print(string)
if len(string) <= 1:
return True
else:
return string[:1] == string[-1:] and rec_palindrome(string[1:-1])
from __future__ import print_function, unicode_literals
import unittest
from palindromes import rec_palindrome, iter_palindrome
class TestPalindrome(unittest.TestCase):
check_true = {'yxxy', '101', 'racecar'}
check_false = {'test', 'fail', 'hihii'}
def test_true(self):
for s in list(self.check_true):
self.assertTrue(rec_palindrome(s))
self.assertTrue(iter_palindrome(s))
def test_false(self):
for s in list(self.check_false):
self.assertFalse(rec_palindrome(s))
self.assertFalse(iter_palindrome(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment