-1

I'm tasked with making a program that finds the longest palindrome in a given text that doesn't contain more than 3 of the same letters.

#This program needs to find the longest palindrome
# that does not contain the same letter more than 3 times

def ispalin(z):
    y = ""
    for i in range(len(z) - 1, -1, -1):
        if z[i] != " ":
            y += z[i]
    if z == y:
        return True
#I'm thinking something needs to be added here, so i can return false
#if the palindrome has more than 3 of the same letter.
    else:
        return False

def haspalin(z, k):
    for i in range(0, len(z) - k + 1):
        if ispalin(z[i:i + k]):
            return (z[i:i + k])
    return False


S = input("Write your text:")
for i in range(len(S), 0, -1):
    z = haspalin(S, i)
    if z:
        print(z)
        break

2 Answers2

3

Try the Counter class of the collections module:

from collections import Counter

x = "absdasbfna"
print(Counter(x))

Output:

Counter({'a': 3, 'b': 2, 's': 2, 'd': 1, 'f': 1, 'n': 1})
CozyCode
  • 484
  • 4
  • 13
  • Ok now i can display the amount of characters in a palindrome. How can i tell it to return False if it has more than 3 of the same character? Like ``` if Counter(z) > 3: return False ``` – Jonathan Andersen Feb 24 '22 at 08:56
  • `not Counter(x)["a"] > 3` That should return the right answer – CozyCode Feb 24 '22 at 11:40
0

Imagine you got the text

text = "abc abcb abcba aba xyz"

Step 1, split the text in words: Here the split method of strings will help you.

words = text.split()

Step 2, check if a word is a palindrome: Here you can use the slicing of arrays.

is_palindrome = word == word[-1::-1]

Step 3, find the repeating letters: Here the answer of @CozyCode will help you.

max_repetition = max(Counter(word).values())

Step 4, find the longest palindrome, here the key argument of max could help you:

longest = max(palindromes, key=lambda word: len(word))

Now you just need to combine these steps:

from collections import Counter
text = "abc abcb abcba aba xyz cdcdcdcdc"
words = text.split()
palindroms = [word for word in words if word==word[-1::-1]]
allowed_palindroms = [
    palindrom for palindrom in palindroms 
    if max(Counter(palindrom).values()) <= 3
]
longest = max(allowed_palindroms, key=lambda word: len(word))
Carlos Horn
  • 1,115
  • 4
  • 17