By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,318 Members | 2,107 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,318 IT Pros & Developers. It's quick & easy.

Plaindromes in Python.

P: 3
How can I implement Plaindromes in Python.
May 7 '19 #1
Share this Question
Share on Google+
1 Reply


P: 7
A palindrome is a phrase, a word, or a sequence that reads the same forward and backward. One such example will be pip! An example of such a phrase will be Ďnurses runí.
Expand|Select|Wrap|Line Numbers
  1. >>> def isPalindrome(string):
  2.       left,right=0,len(string)-1
  3.       while right>=left:
  4.               if not string[left]==string[right]:
  5.                        return False
  6.               left+=1;right-=1
  7.               return True
  8. <span style="font-weight: 400">>>> isPalindrome('redrum murder')</span>
  9. True
  10.  
  11. >>> isPalindrome('CC.')
  12. False
  13.  
  14. Well, there are other ways to do this too. Letís try using an iterator.
  15.  
  16. >>> def isPalindrome(string):
  17.       left,right=iter(string),iter(string[::-1])
  18.       i=0
  19.       while i<len(string)/2:
  20.              if next(left)!=next(right):
  21.                       return False
  22.              i+=1
  23.              return True
  24. >>> isPalindrome('redrum murder')
  25. True
  26.  
  27. >>> isPalindrome('CC.')
  28. False
  29.  
  30. >>> isPalindrome('CCC.')
  31. False
  32.  
  33. >>> isPalindrome('CCC')
  34. True
  35.  
  36.  
May 11 '19 #2

Post your reply

Sign in to post your reply or Sign up for a free account.