Apr 07 2010
Apr 07 2010
Palindromic sub-sequences in python
This bit of code returns all palindromic subsequences in the input string. If the line marked #In-efficient is better implemented (I am lazy), the running time is O(n2). Can you find a better solution?
palindrome.py1 #!/usr/bin/env python 2 3 def get_palindromes(str): 4 """ Return all palindromes in str of minimum size 3 """ 5 length = len(str) + 1 6 7 found = [] 8 for i in xrange(0, length): 9 for j in xrange(i+3, length): 10 mid = i + ((j - i) / 2) 11 if str[i:mid] == str[mid+1:j][::-1]: # In-efficient 12 found.append(str[i:j]) 13 return found 14 15 if __name__ == '__main__': 16 print get_palindromes('efeababaf')