How can I implement Plaindromes in Python.
Plaindromes in Python.
Collapse
X
-
Tags: None
-
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’.
Code:>>> def isPalindrome(string): left,right=0,len(string)-1 while right>=left: if not string[left]==string[right]: return False left+=1;right-=1 return True <span style="font-weight: 400">>>> isPalindrome('redrum murder')</span> True >>> isPalindrome('CC.') False Well, there are other ways to do this too. Let’s try using an iterator. >>> def isPalindrome(string): left,right=iter(string),iter(string[::-1]) i=0 while i<len(string)/2: if next(left)!=next(right): return False i+=1 return True >>> isPalindrome('redrum murder') True >>> isPalindrome('CC.') False >>> isPalindrome('CCC.') False >>> isPalindrome('CCC') True
Comment