Answer to Question #292619 in Python for Dhanaraju

Question #292619

Swap Letters


Anil is given a sentense S.He tries to make this sentence special.A sentence can be made special by swapping the character with the highest frequency with the character having the lowest frequency in the sentence.Help Anil by transforming the sentence into a special Sentence.

Note:

Consider Upper and lower case letters as different.

If there are multiple letters with the same frequency, choose the lower case letter that comes earliest in dictionary order.

a.If letters like x and B have the same frequency consider x.

b.If letters like x and b have the same frequency consider b.


Input

The first line of input is a string.


sample input1

Python is a programming language.

sample output1

Python is e progremming lenguega.


sample input2

CHECK your blood PRESSURE frequently.

sample output2

CHECK ybur olbbd PRESSURE frequently.


1
Expert's answer
2022-02-02T05:09:43-0500
def selectLetter(ch1, ch2):
    if 'a' <= ch1 <= 'z' and 'A' <= ch2 <= 'Z':
        return ch1
    if 'a' <= ch2 <= 'z' and 'A' <= ch1 <= 'Z':
        return ch2
    if ch1 < ch2:
        return ch1
    return ch2


def specialSentence(s):
    D = {}
    for ch in s:
        if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
            D[ch] = D.get(ch, 0) + 1
    
    minFr = len(s)+1
    lessFrCh = None
    maxFr = 0
    moreFrCh = None
    for ch in D:
        if D[ch] < minFr:
            minFr = D[ch]
            lessFrCh = ch
        elif D[ch] == minFr:
            lessFrCh = selectLetter(ch, lessFrCh)
        
        if D[ch] > maxFr:
            maxFr = D[ch]
            moreFrCh = ch
        elif D[ch] == maxFr:
            moreFrCh = selectLetter(ch, moreFrCh)
    
    res = ''
    for ch in s:
        if ch == lessFrCh:
            res += moreFrCh
        elif ch == moreFrCh:
            res += lessFrCh
        else:
            res += ch

    return res


def main():
    s = input()
    ss = specialSentence(s)
    print(ss)


main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS