How to check for palindrome using Python logic [closed]

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to check for palindrome using Python logic [closed] and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to check for palindrome using Python logic [closed], which can be followed any time. Take easy to follow this discuss.

How to check for palindrome using Python logic [closed]

I’m trying to check for a palindrome with Python. The code I have is very for-loop intensive.

And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it’s just not making the most of the language.

I see on this website. Search for “C-style for”, that Python doesn’t have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.

I’ve tried looking around, I can’t find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?

I’ve done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.

def isPalindrome(n):
    lst = [int(n) for n in str(n)]
    l=len(lst)
    if l==0 || l==1:
        return True
    elif len(lst)%2==0:
        for k in range (l)
        #####
    else:
        while (k<=((l-1)/2)):
            if (list[]):
                #####   
for i in range (999, 100, -1):
    for j in range (999,100, -1):
        if isPalindrome(i*j):
            print(i*j)
            break

I’m missing a lot of code here. The five hashes are just reminders for myself.

Concrete questions:

  1. In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?

  2. My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?

  3. Does anybody have any good advice, or good websites, or resources for people in my position? I’m not a programmer, I don’t aspire to be one, I just want to learn enough so that when I write my bachelor’s degree thesis (electrical engineering), I don’t have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. “How to go from basic C to great application of Python”, that sort of thing.

  4. Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops…

PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.

Asked By: DrOnline

||

Answer #1:

A pythonic way to determine if a given value is a palindrome:

str(n) == str(n)[::-1]

Explanation:

  • We’re checking if the string representation of n equals the inverted string representation of n
  • The [::-1] slice takes care of inverting the string
  • After that, we compare for equality using ==
Answered By: Óscar López

Answer #2:

An alternative to the rather unintuitive [::-1] syntax is this:

>>> test = "abcba"
>>> test == ''.join(reversed(test))
True

The reversed function returns a reversed sequence of the characters in test.

''.join() joins those characters together again with nothing in between.

Answered By: RichieHindle

Answer #3:

Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using while and for loops):

def is_palindrome(word):
    letters = list(word)
    is_palindrome = True
    i = 0
    while len(letters) > 0 and is_palindrome:
        if letters[0] != letters[(len(letters) - 1)]:
            is_palindrome = False
        else:
            letters.pop(0)
            if len(letters) > 0:
                letters.pop((len(letters) - 1))
    return is_palindrome

And….the second one:

def is_palindrome(word):
    letters = list(word)
    is_palindrome = True
    for letter in letters:
        if letter == letters[-1]:
            letters.pop(-1)
        else:
            is_palindrome = False
            break
    return is_palindrome

Answer #4:

The awesome part of python is the things you can do with it. You don’t have to use indexes for strings.

The following will work (using slices)

def palindrome(n):
    return n == n[::-1]

What it does is simply reverses n, and checks if they are equal. n[::-1] reverses n (the -1 means to decrement)

“2) My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?”

Regarding the above, you want to use xrange instead of range (because range will create an actual list, while xrange is a fast generator)

My opinions on question 3

I learned C before Python, and I just read the docs, and played around with it using the console. (and by doing Project Euler problems as well 🙂

Answered By: jh314

Answer #5:

Below the code will print 0 if it is Palindrome else it will print -1

Optimized Code

word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output:
0

word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome

Output:
-1

Explaination:

when searching the string the value that is returned is the value of the location that the string starts at.

So when you do word.find(word[::-1]) it finds nepalapen at location 0 and [::-1] reverses nepalapen and it still is nepalapen at location 0 so 0 is returned.

Now when we search for nepalapend and then reverse nepalapend to dnepalapen it renders a FALSE statement nepalapend was reversed to dnepalapen causing the search to fail to find nepalapend resulting in a value of -1 which indicates string not found.


Another method print true if palindrome else print false

word = "nepalapen"
print(word[::-1]==word[::1])

output:
TRUE

Answered By: Ganesh Pandey

Answer #6:

There is also a functional way:

def is_palindrome(word):
  if len(word) == 1: return True
  if word[0] != word[-1]: return False
  return is_palindrome(word[1:-1])
Answered By: Khozzy

Answer #7:

I know that this question was answered a while ago and i appologize for the intrusion. However,I was working on a way of doing this in python as well and i just thought that i would share the way that i did it in is as follows,

word = 'aibohphobia'
word_rev = reversed(word)
def is_palindrome(word):
    if list(word) == list(word_rev):
        print'True, it is a palindrome'
    else:
        print'False, this is''t a plindrome'
is_palindrome(word)
Answered By: sanster9292

Answer #8:

There is much easier way I just found. It’s only 1 line.

is_palindrome = word.find(word[::-1])
Answered By: Inna Bohdanova

Leave a Reply

Your email address will not be published.