Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I don't know how to fix.

+5 votes
asked Jan 14, 2022 by Sam (1,310 points)

1 Answer

0 votes
answered Jan 14, 2022 by Peter Minarik (84,720 points)
edited Jan 14, 2022 by Peter Minarik

Your function is_palindrome has some bugs. If you run it, you'll see the error message:

Traceback (most recent call last):
  File "main.py", line 22, in <module>
    main();
  File "main.py", line 18, in main
    print(f"{_:>18} : {is_palindrome(_)}");
  File "/home/palindrome.py", line 26, in is_palindrome
    while (i<=v and s [o]==s [i]):
IndexError: string index out of range

It's saying that you're indexing your string with an index that is outside of the boundaries of your string. A string str has the boundaries [0, len(str) - 1] (left and right sides inclusive).

I think in your code you run from a lower index (i) and an upper index (o) toward each other and compare the characters from the beginning and the end of the string. However, you initialized the upper index to be -1, which is wrong.

In the end you should check if your upper index is outside of the bounds of your string, that is, even the last character was verified.

So fixing all of these above, your code could look something like below:

def is_palindrome(s):
    v = len(s)
    i = 0
    o = v - 1
    while (i < v and s[o] == s[i]):
        i += 1
        o -= 1
    if (i == v):
        return True
    else:
        return False

If you would like to optimize your code, you can. For instance, you may realize that there is no need for both i and o to go from 0 to the full length of the string. They could meet in the middle of the string. ;) I leave you to add this optimization if you will.

Good luck!

commented Jan 14, 2022 by Sam (1,310 points)
thanks I realize what ur saying but I think I need o the way it was but this helped
commented Jan 14, 2022 by Sam (1,310 points)
nevermind yours worked but not mine
commented Jan 14, 2022 by Peter Minarik (84,720 points)
I'm glad you're sorted.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...