Search code examples
pythonpalindrome

Unique length-3 palindromes python


i have this problem where you have to find all length three palindromes and print how many there are.

For example:

aabca

Output:

3
aba
aaa
aca

I already know how to get the num for how many there are with the code i found on the web below:

res = 0
unq_str = set(s)
for ch in unq_str:
    st = s.find(ch)
    ed = s.rfind(ch)
    if st<ed:
        res+=len(set(s[st+1:ed]))

return res

but thats only for the num

so i tried on the concept where you iterate through it and take lists with length three and check if it is a palindrome

for x in range(len(input1)):
    if not x < 3:
        Str1 = input1[x-3:x]

but then i stopped because it doesn't go for any kind of combination

is there any way to do this?

thanks


Solution

  • I'm not 100% sure this is correct but hopefully it will put you on the correct track.

    import itertools
    
    input = "aabca"
    palindromes = set() # use a set to ensure no duplicates
    
    # iterate over all combinates of length 3
    for t in itertools.combinations(input, 3):
        # is this a palindrome? If so save
        if t == tuple(reversed(t)):
            palindromes.add(''.join(t))
    
    # output results
    print(palindromes)
    print(len(palindromes))
    

    There may be an itertools recipe which doesn't generate duplicates but I think this works.

    Edit: Using join results in a set of strings rather than string characters.

    Edit2: To make this equivalent to keithpjolly's answer:

    import itertools
    
    input = "aabca"
    palindromes = set() # use a set to ensure no duplicates
    
    # iterate over all combinates of length 3
    for a,b,c in itertools.combinations(input, 3):
        # is this a palindrome? If so save
        if a == c:
            palindromes.add(''.join((a,b,c)))
    
    
    # output results
    print(palindromes)
    print(len(palindromes))