Last active
August 16, 2020 09:25
-
-
Save antony-jr/bb65362d1b9d67c2ac85e8f9a414ba33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import datetime | |
# The main class which forms N Palindromes. | |
class NPalindrome(object): | |
def __init__(self, n, string): | |
self.N = n | |
self.String = string | |
self.Possible = False | |
self.Palindromes = list() | |
def __check(self, string): | |
return string == string[::-1] | |
def __compute(self, string, n): | |
if n == 1: | |
if self.__check(string): | |
self.Palindromes.append(string) | |
return True | |
else: | |
return False | |
substring = [] | |
index = 0 | |
for char in string: | |
substring.append(char) | |
index += 1 | |
form = ''.join(substring) | |
if self.__check(form) and self.__compute(string[index:], n-1): | |
self.Palindromes.append(form) | |
return True | |
return False | |
def compute(self): | |
self.Palindromes.clear() | |
self.Possible = self.__compute(self.String, self.N) | |
self.Palindromes.reverse() # Rearrange the palindrome in correct order | |
return self.Possible | |
def isPossible(self): | |
return self.Possible | |
def getPalindromes(self): | |
return self.Palindromes | |
string = str(input("Enter input string: ")) | |
ThreePalindromes = NPalindrome(3, string) | |
started = datetime.datetime.now() | |
ThreePalindromes.compute() | |
elapsed = datetime.datetime.now() - started | |
if not ThreePalindromes.isPossible(): | |
print("Result: Impossible") | |
else: | |
print("Result: {}".format(ThreePalindromes.getPalindromes())) | |
print("Computed Under: {} Seconds ({} Microseconds).".format(elapsed.total_seconds(), elapsed.microseconds)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment