1

This is a program of finding a string is palindrome or not. But When I run this code I got error "standard output is error".

class Palindrome:
  @staticmethod
  def is_palindrome(word):
    flag = word;
    lengths = len(word);
    j=lengths;
    lengths = lengths/2;
    lengths = int(lengths);
    for i in lengths:
        if (word[i] == word[j]):
            count = count+1;
            j = j-1;
    if (count == lengths):
        r = "yes";
    else:
        r = "no";
    return r
word = input();
print(Palindrome.is_palindrome(word));
Sharif
  • 533
  • 2
  • 6
  • 11

1 Answers1

1

There are some mistakes in the code,

First of all, you are trying to iterate a int like for i in lengths which will throw you an error. You must be using it like for i in range(lengths).

Also, you are trying to do count = count+1 even before count is initialized, which will be throwing an error. To solve this you can initialize the variable count before the loop to 0.

Another issue with the code is that, you are tying to compare word[i] and word[j] where j is length which is not possible because for a string of length n, index runs from 0 to n-1. Therefore you must be using length-1 as j.

Also, there is no need for semicolon in Python.

Correcting all the things that I have mentioned above you can re-write the code like this

class Palindrome:
    @staticmethod
    def is_palindrome(word):
        flag = word
        lengths = len(word)
        j=lengths-1
        lengths = lengths/2
        lengths = int(lengths)
        count = 0
        for i in range(lengths):
            if (word[i] == word[j]):
                count = count+1
                j = j-1
        if (count == lengths):
            r = "yes"
        else:
            r = "no"
        return r
word = input()
print(Palindrome.is_palindrome(word))

If you can use ~ operator you can tidy up the code to a great extend. It can be done like this.

class Palindrome:
    @staticmethod
    def is_palindrome(word):
        if all(word[i] == word[~i] for i in range(len(word) // 2)):
            return "yes"
        else:
            return "no"

word = input()
print(Palindrome.is_palindrome(word)

If you want to know how the ~ operator works take a look at this post.

You can improve it further if you can use indexing to reverse the string. If you can reverse the string and then check with the original one.

class Palindrome:
    @staticmethod
    def is_palindrome(word):
        if word == word[::-1]:
            return "yes"
        else:
            return "no"

word = input()
print(Palindrome.is_palindrome(word)
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108