Home > OS >  how to add this both original_text and reversed_text attributes in this class? how should I fix it t
how to add this both original_text and reversed_text attributes in this class? how should I fix it t

Time:11-02

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?

CodePudding user response:

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())
  • Related