Answer to Question #319870 in Python for Gaya

Question #319870

Anil is given a sentence s. He tries to make this sentence special. A sentence can be mads special by swapping the character with the highest frequency with character having lowest frequency in the sentence. Help anil by transfering sentence into a special sentence.



Note: upper and lower case letters are different



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



* If letters like X and B have same frequency consider X



If x and b have same frequency consider b.



Input: python is a programming language



Output: python is e progremming lenguega




Need correct output sir.

1
Expert's answer
2022-03-28T16:10:59-0400
def char_freq(s):
    """Return the most and the list frequent characters 
       in the string"""
    fr = {}
    for ch in s:
        if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
            fr[ch] = fr.get(ch, 0) + 1
    
    max_fr = 0
    min_fr = len(s)
    for ch in fr:
        if fr[ch] > max_fr:
            max_fr = fr[ch]
            max_ch = ch
        if fr[ch] == max_fr and ch < max_ch:
            max_ch = ch
        
        if fr[ch] < min_fr:
            min_fr = fr[ch]
            min_ch = ch
        if fr[ch] == min_fr and ch < min_ch:
            min_ch = ch
    return max_ch, min_ch


def swap_char(s, ch1, ch2):
    """Return the copy of a string s in which charcters
       ch1 and ch2 are swaped"""
    res = ''
    for ch in s:
        if ch == ch1:
            res += ch2
        elif ch == ch2:
            res += ch1
        else:
            res += ch
    return res


def main():
    line = input()
    ch1, ch2 = char_freq(line)
    res = swap_char(line, ch1, ch2)
    print(res)


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