john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

palindrome word recursion iterative

def is_palindrome( text ):
  if len( text ) < 2:
    return True
  if text[0] == text[-1]:
    return is_palindrome( text[1:-1] )
  return False


def is_palindrome_it( text ):
  while len( text ) >1:
    if text[0] != text[-1]:
      return False
    text = text[1:-1]
  return True

def run_tests( method ):
  print 'is palindrome?'
  tests = ['a', '', '0' , 'aa' , 'aba', 'abba']
  for text in tests:
    assert method( text ) == True
    print text, 'YES'
  print 'ab', str( method( 'ab' ))
  print 'abab', str( method( 'abab' ))
  print 'cabba', str( method( 'cabba' ))
  print 'rats live on no evil star', str( method( 'rats live on no evil star' ))

run_tests( is_palindrome )
run_tests( is_palindrome_it )
print 'done'

  • « Unrar rarcrack
  • binary search tree »

Published

Jul 21, 2013

Category

python

~93 words

Tags

  • iterative 2
  • palindrome 1
  • python 180
  • recursion 1
  • word 3