Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Different ways to check if string is a palindrome in Python
from timeit import timeit
def is_palindrome(input):
return input == reduce(lambda x, y: y + x, input)
def is_palindrome2(input):
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
return input == input[reverse_slice]
def is_palindrome3(input):
return input == ''.join(reversed(input))
def is_palindrome4(input):
return input == input[::-1]
if __name__ == '__main__':
assert is_palindrome("dupa") is False
assert is_palindrome("blaalb") is True
assert is_palindrome2("dupa") is False
assert is_palindrome2("blaalb") is True
assert is_palindrome3("dupa") is False
assert is_palindrome3("blaalb") is True
assert is_palindrome4("dupa") is False
assert is_palindrome4("blaalb") is True
print 'lambda expression: ' +\
str(timeit(stmt="is_palindrome(\"blaaaaaalb\")",
setup="from __main__ import is_palindrome",
number=10**5))
print 'referenced slice: ' +\
str(timeit(stmt="is_palindrome2(\"blaaaaaalb\")",
setup="from __main__ import is_palindrome2",
number=10**5))
print 'reversing list of characters: ' +\
str(timeit(stmt="is_palindrome3(\"blaaaaaalb\")",
setup="from __main__ import is_palindrome3",
number=10**5))
print 'extended slice: ' +\
str(timeit(stmt="is_palindrome4(\"blaaaaaalb\")",
setup="from __main__ import is_palindrome4",
number=10**5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.