4

is there any patterns i can use to sort out how to create a string that is palindrome which made up with 'X' 'Y'

2 Answers2

5

Let's assume n is even. Generate every string of length n/2 that consists of x and y, and append its mirror image to get a palindrome.

Exercise 1: prove that this generates all palindromes of length n.

Exercise 2: figure out what to do when n is odd.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • when n is odd, just let the middle one be x or y, then append x/y to every string of length (n-1)/2 and its reverse version,is that right? – user3426141 Mar 16 '14 at 16:41
  • @user3426141: Yes (provided by "x or y" you mean "each of x and y"). – NPE Mar 16 '14 at 16:41
  • dont know where to start to generate string, base case should be n=0 and 1? – user3426141 Mar 16 '14 at 16:43
  • @user3426141: There's many ways to do this: recursively; by generating integers between 0 and 2**n-1 and looking at their binary representation (0->x, 1->y); by using `itertools.product`; etc. Take your pick. – NPE Mar 16 '14 at 16:46
  • how to do it recursively? since string unlike list, it is immutatable – user3426141 Mar 16 '14 at 16:52
  • 1
    @user3426141 You can always use a list and make string out of it in the end, if that floats your boat better. But there's no need to, you can implement this in a totally purely functional way (no mutation) – Niklas B. Mar 16 '14 at 17:36
0

First generate all possible strings given a list of characters:

>>> from itertools import product
>>> characters = ['x','y']
>>> n = 5
>>> [''.join(i) for i in product(characters, repeat=n)]
['xxxxx', 'xxxxy', 'xxxyx', 'xxxyy', 'xxyxx', 'xxyxy', 'xxyyx', 'xxyyy', 'xyxxx', 'xyxxy', 'xyxyx', 'xyxyy', 'xyyxx', 'xyyxy', 'xyyyx', 'xyyyy', 'yxxxx', 'yxxxy', 'yxxyx', 'yxxyy', 'yxyxx', 'yxyxy', 'yxyyx', 'yxyyy', 'yyxxx', 'yyxxy', 'yyxyx', 'yyxyy', 'yyyxx', 'yyyxy', 'yyyyx', 'yyyyy']

Then filter out non-palindrome:

>>> n = 4
>>> [''.join(i) for i in product(characters, repeat=n) if i[:n/2] == i[::-1][:n/2]]
['xxxx', 'xyyx', 'yxxy', 'yyyy']
>>> n = 5
>>> [''.join(i) for i in product(characters, repeat=n) if i[:n/2] == i[::-1][:n/2]]
['xxxxx', 'xxyxx', 'xyxyx', 'xyyyx', 'yxxxy', 'yxyxy', 'yyxyy', 'yyyyy']

If you don't like if conditions in list comprehension, you can use filter():

>>> from itertools import product
>>> characters = ['x','y']
>>> n = 5
>>> def ispalindrome(x): return x[:n/2] == x[::-1][:n/2];
>>> filter(ispalindrome, [''.join(i) for i in product(characters, repeat=n)])
['xxxxx', 'xxyxx', 'xyxyx', 'xyyyx', 'yxxxy', 'yxyxy', 'yyxyy', 'yyyyy']
alvas
  • 115,346
  • 109
  • 446
  • 738