Search code examples
python-3.xalgorithmlistdictionarypalindrome

How to append and join the center element(when occuring more than once) in a palindrome


I want to make a palindrome lexicographically from a user input string

I take the input string and count each alphabet's occurrence(odd or even) and store them accordingly in a dictionary. Then, I find the centre element and also store the left and right parts in a sorted manner.

Now, how do I continue when the centre element has multiple occurrences?

from collections import Counter
even={}
odd={}
s=input()
s=list(s)
s.sort()
s=Counter(s)
for i,j in s.items():
    if j%2==0:
        even.update({i:j})
    else:
        odd.update({i:j})
print(even,odd)        

od=list(odd)   
ev=list(even)

if len(odd)==1:
    center=od[0]
elif len(odd)>1:
    print('Not Possible')
elif len(odd)==0:
    center=''

right=[]

for i,j in even.items():
    right.append(i*int(j/2))

print(right)         
left=right[::-1]
print(left)

pal=right+list(center)+left

palin=''.join(pal)
print(palin)

For example, when the input is crocorc, Output should be corcroc, But I am stuck at orcrc.


Solution

  • You can check for multiple occurrences of centre element, and add the extra elements in the even list:

    if odd[od[0]] > 1:
        even[od[0]] = odd[od[0]] - 1
    

    We do a -1 because we have to use one element as the centre element. Now the issue will be that even will not be sorted so you need to sort it.

    even = sorted(even.items(), key=lambda kv: kv[0])
    import collections
    even = collections.OrderedDict(even)
    

    First line of code above sorts even which returns a list of tuples, and third line converts it back to dictionary.

    Here is the finished code

    from collections import Counter
    even={}
    odd={}
    s=input()
    s=list(s)
    s.sort()
    s=Counter(s)
    for i,j in s.items():
        if j%2==0:
            even.update({i:j})
        else:
            odd.update({i:j})
    print(even,odd)        
    
    od=list(odd)   
    ev=list(even)
    
    if len(odd)==1:
        center=od[0]
    elif len(odd)>1:
        print('Not Possible')
    elif len(odd)==0:
        center=''
    
    if odd[od[0]] > 1:
        even[od[0]] = odd[od[0]] - 1
    
    right=[]
    
    even = sorted(even.items(), key=lambda kv: kv[0])
    import collections
    even = collections.OrderedDict(even)
    
    for i,j in even.items():
        right.append(i*int(j/2))
    
    print(right)         
    left=right[::-1]
    print(left)
    
    pal=right+list(center)+left
    
    palin=''.join(pal)
    print(palin)