very new to programming and I am trying to solve a few Project Euler problems. I would like to know for a python code which identifies palindrome and non-palindrome. What is the most efficient way to do this? could you please show the code you find most efficient for this problem.
Asked
Active
Viewed 7,243 times
1
-
2What have you tried so far? What do you think would be the most efficient way to do it? – Jul 18 '15 at 04:11
-
Having done many many project euler questions with a `def isPali(x): return x==int(str(x)[::-1])`, I can tell you that it's not your palindrome check where you'll be wasting time. There's usually somewhere else to pull time from :P – NightShadeQueen Jul 18 '15 at 04:22
-
When you are writing your question, a list called "***Questions that may already have your answer***" appears. **Use** it. You can even use a fancy feature in your browser called "tabs" to open more than one page at once so you don't lose your place. – MattDMo Jul 18 '15 at 05:06
-
1No need to be a jerk about it. – user3667054 Jul 20 '15 at 05:58
2 Answers
3
You can do this very simply by just checking if the string that you input is equal to itself reversed (that's what a palindrome is).
def check_palindrome(s):
return s == s[::-1]
[::-1]
reverses the string because the -1
tells how many steps to go by and negative will go through the string in reverse.
If you will need to check if integers are palindromes, you can do:
def check_palindrome(s):
return str(s) == str(s)[::-1]

michaelpri
- 3,521
- 4
- 30
- 46
2
I'm a big fan of simplicity over (potentially false) optimizations. Start with something straight forward, and move on from there:
def is_palindrom(s):
length = len(s)
for i in range(length / 2):
if s[i] != s[length - i - 1]:
return False
return True

Mureinik
- 297,002
- 52
- 306
- 350
-
4
-
Just a note that this will not work for odd lengthed palindromes – Spencer Wieczorek Jul 18 '15 at 04:17
-
@Mureinik That and you need to make the `range` a integer, `range(math.floor(length / 2))`. – Spencer Wieczorek Jul 18 '15 at 04:23
-
@SpencerWieczorek Without any version specification, I just assumed OP meant Python 2. In Python 3 you would be correct, of course. – Mureinik Jul 18 '15 at 04:31
-
lordy how many versions of python are they? and are they relatively the same? – user3667054 Jul 18 '15 at 04:35
-
@user3667054 Many, but the two people care about are 2.7 and 3.4 and those two are not compatible with each other. Personally, I like `range(length//2)` no matter which version I'm using, because it'll work the same for both. But they're not too different. – NightShadeQueen Jul 18 '15 at 04:39
-
"The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet." — Michael A. Jackson – Dleep Jul 18 '15 at 05:05