So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself) Condition: spaces inbetween ch
I have to agree the solution may seem to complicated, i think the best solution, to find the largest palindrome in a subsequence, (considering characters in between for example in 'character' the largest palindrome should be carac) is:
def find_char_backwards(a, c):
for i in range(len(a) - 1, -1,-1):
if a[i] == c:
index=i
return True, index
return False, 0
def longest_palindorme(a):
if len(a) < 2:
return a
else:
c=a[0]
(exist_char,index) = find_char_backwards(a[1:],c)
if exist_char:
palindrome=[c] + longest_palindorme(a[1:index+1]) + [c]
else:
palindrome=[]
rest_palidorme=longest_palindorme(a[1:])
if len(palindrome)>len(rest_palidorme):
return palindrome
else:
return rest_palidorme
Where a is an array, this solution uses recursion, and dynamic programming
Use a nested loop:
for x in range(len(body)):
for y in range(len(body)):
...
Your solution seems a bit complicated to me. Just look at all of the possible substrings and check them individually:
def palindromes(text):
text = text.lower()
results = []
for i in range(len(text)):
for j in range(0, i):
chunk = text[j:i + 1]
if chunk == chunk[::-1]:
results.append(chunk)
return text.index(max(results, key=len)), results
text.index()
will only find the first occurrence of the longest palindrome, so if you want the last, replace it with text.rindex()
.
The following function returns the longest palindrome contained in a given string. It is just slightly different in that it uses itertools
as suggested in this answer. There is value in abstracting away the combination generation. Its time complexity is evidently still cubic. It can trivially be adapted as needed to return the index and/or the list of palindromes.
import itertools
def longest_palindrome(s):
lp, lp_len = '', 0
for start, stop in itertools.combinations(range(len(s)+1), 2):
ss = s[start:stop] # substring
if (len(ss) > lp_len) and (ss == ss[::-1]):
lp, lp_len = ss, len(ss)
return lp
I have made function name as maxpalindrome(s) in this one string argument 's'. This function will return longest possible palindrome sub string and length of substring...
def maxpalindrome(s):
if len(s) == 1 or s == '':
return str(len(s)) + "\n" + s
else:
if s == s[::-1]:
return str(len(s)) + "\n" + s
else:
for i in range(len(s)-1, 0, -1):
for j in range(len(s)-i+1):
temp = s[j:j+i]
if temp == temp[::-1]:
return str(len(temp)) +"\n"+temp
value ="Madamaaamadamaaaacdefgv"
longestPalindrome =""
lenght =0;
for i in range(len(value)):
for j in range(0, i):
array = value[j:i + 1]
if (array == array[::-1] and len(longestPalindrome) < len(array)):
longestPalindrome =array
print(longestPalindrome)