Search code examples
pythonpython-3.xpalindrome

how to add this both original_text and reversed_text attributes in this class? how should I fix it to get the ideal outputs?


Below are the ideal outputs:

'''

>>> palindrome = Palindrome('eye')
>>> palindrome.original_text
'eye'
>>> palindrome.reversed_text
'eye'
>>> palindrome.is_palindrome()
True
>>> palindrome = Palindrome('dye')
>>> palindrome.original_text
'dye'
>>> palindrome.reversed_text
'eyd'
>>> palindrome.is_palindrome()
False

'''

My code:

class Palindrome :

def __init__(self,number) :
    self.num = number
    
def is_palindrome(self) :

    temp = self.num
    result = 0

    while(temp != 0) :
        
        rem = temp % 10

        result =  result * 10 + rem

        temp //= 10

    if self.num == result :
        return True
    else :
        return False

How to add this both original_text and reversed_text attributes in this class? How should I fix the code above to obtain the ideal results?


Solution

  • You can use python's built-in power to make your code more readible and simple. Something like this should work:

    class Palindrome :
    
        def __init__(self, data):
            data = str(data)
            self.original_text = data
            self.reversed_text = data[::-1]
    
        def is_palindrome(self):
            return self.original_text == self.reversed_text
       
            
    palindrome = Palindrome('eye')
    print(palindrome.original_text)
    print(palindrome.reversed_text)
    print(palindrome.is_palindrome())
    
    palindrome = Palindrome('dye')
    print(palindrome.original_text)
    print(palindrome.reversed_text)
    print(palindrome.is_palindrome())