palindrome/transform/Transform.py

59 lines
2.4 KiB
Python
Raw Normal View History

2021-03-17 09:32:45 +00:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Transform(object):
"""Class to transform a given integer into a palindrome"""
2021-03-17 13:25:22 +00:00
# to avoid magic numbers.
MAXIMUM_INPUT_VALUE = 1000000000
INVALID_RETURN_VALUE = -1
2021-03-17 09:32:45 +00:00
def __init__(self):
super(Transform, self).__init__()
2021-03-17 13:25:22 +00:00
def palindrome(self, integer):
2021-03-17 11:37:54 +00:00
'''
2021-03-17 13:25:22 +00:00
The main function. Checks if input integer is already a palindrome
and trys calculating one if input integer is not already a palindrome.
2021-03-17 11:37:54 +00:00
'''
2021-03-17 13:25:22 +00:00
self.input_integer = integer
if self.__is_palindrome(self.input_integer):
print('Integer {} is a palindrome'.format(self.input_integer))
return self.input_integer
2021-03-17 11:37:54 +00:00
else:
2021-03-17 13:25:22 +00:00
print('Integer {} is not a palindrome'.format(self.input_integer))
2021-03-23 13:46:08 +00:00
print('Calculating the palindrome for input {}'.format(self.input_integer)) # noqa
2021-03-17 11:37:54 +00:00
palindrome = self.__calculate_palindrome()
return palindrome
# The following methods are private. Signaled by the leading __
def __is_palindrome(self, int_to_check):
2021-03-17 13:25:22 +00:00
reversed_integer = self.__reverese_int(int_to_check)
if self.input_integer == reversed_integer:
2021-03-17 11:37:54 +00:00
return True
else:
return False
def __reverese_int(self, int_to_reverse):
2021-03-17 13:25:22 +00:00
reversed_integer = 0
2021-03-17 11:37:54 +00:00
int_to_check = int_to_reverse
while int_to_check > 0:
reminder = int_to_check % 10
2021-03-17 13:25:22 +00:00
reversed_integer = (reversed_integer * 10) + reminder
2021-03-17 11:37:54 +00:00
int_to_check = int_to_check // 10
2021-03-17 13:25:22 +00:00
return reversed_integer
2021-03-17 11:37:54 +00:00
def __calculate_palindrome(self):
2021-03-17 13:25:22 +00:00
reversed_integer = self.__reverese_int(self.input_integer)
self.input_integer = self.input_integer + reversed_integer
print('Possible palindrome is {}'.format(self.input_integer))
if self.__is_palindrome(self.input_integer) is True:
print('Possible palindrome is correct!')
return self.input_integer
elif not self.__is_palindrome(self.input_integer):
print('Possible palindrome is wrong! Calcualte again!')
while not self.__is_palindrome(self.input_integer):
if self.input_integer >= self.MAXIMUM_INPUT_VALUE:
return self.INVALID_RETURN_VALUE
else:
self.__calculate_palindrome()
return self.input_integer