Answer to Question #323053 in Python for sandhya

Question #323053

Anil is given a sentence as he tries to make a sentence special a sentence can be made special by swapping the character with high frequency with the character character has low frequency in the sentence help anil by transforming the sentence into a special sentence in python

swap most frequent letter with least given a sentence swap the occurences of the most frequent with the least frequent letter and vice-versa

note: consider upper & lower case letters as different .if there are multiple letters with the same frequencies choose the lower case letter that comes earliest in dictionary order O


input: Python is a programming language

o/p: Python is e progremming lenguega


input: Check your blood preeusre frequently

o/p: Check ybur olbbd preeusre frequently


1
Expert's answer
2022-04-03T16:10:13-0400
def minMaxFr(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
    minCh = None
    maxFr = 0
    maxCh = None
    for ch in D:
        if D[ch] < minFr:
            minFr = D[ch]
            minCh = ch
        elif D[ch] == minFr and ch.lower() < minCh.lower():
            minCh = ch
        
        if D[ch] > maxFr:
            maxFr = D[ch]
            maxCh = ch
        elif D[ch] == maxFr and ch.lower() < maxCh.lower():
            maxCh = ch
    return minCh, maxCh
    


def swap(s, ch1, ch2):
    res = ''
    for ch in s:
        if ch == ch1:
            res += ch2
        elif ch == ch2:
            res += ch1
        else:
            res += ch

    return res


def main():
    s = input()
    chMin, chMax = minMaxFr(s)
    s = swap(s, chMin, chMax)
    print(s)


if __name__ == '__main__':
    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