[Edit: as someone remarked, I misused the concept of a palindrome, now I have edited using the correct functions. I also made some optimizations in the first and third examples in which the for statement reaches half the line]
I encoded three different versions for a method that checks if a string is a palindrome. This method is implemented as extensions to the class "str"
Methods also convert the string to lowercase and remove all punctual and whitespace. Which one is better (faster, pythons)?
Here are the methods:
1) This is the first solution I was thinking about:
def palindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) n = len(lowerself) for i in range(n//2): if lowerself[i] != lowerself[n-(i+1)]: return False return True
I think this is faster because there are no conversions or line reversals, and the for statement breaks into the first separate element, but I don't think this is an elegant and pythonic way to do this
2) In the second version, I am doing a conversion with a solution based here on stackoverflow (using the extended string slicing [:: - 1])
# more compact def pythonicPalindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) lowerReversed = lowerself[::-1] if lowerself == lowerReversed: return True else: return False
But I think that slicing and comparing strings makes this solution slower.
3) The third solution I was thinking of is using an iterator:
# with iterator def iteratorPalindrom(self): lowerself = re.sub("[ ,.;:?!]", "", self.lower()) iteratorReverse = reversed(lowerself) for char in lowerself[0:len(lowerself)//2]: if next(iteratorReverse) != char: return False return True
which I find more elegant from the first solution and more effective from the second solution