0

I just want to clear out that I am new to coding. I am trying to solve a problem set that counts the occurrence of characters in a string and prints out the 3 most reoccurring characters

Heres the code I wrote

    s = input().lower()
    b =  []
    for i in s:
        templst = []
        templst.append(i)
        templst.append(s.count(i))
        if templst not in b:
            b.append(templst)

    final = sorted(b, key=itemgetter(1),reverse=True)
    print (final)
    for i in final[:3]:
        print(*i, sep=" ")

now if I gave it an input of

szrmtbttyyaymadobvwniwmozojggfbtswdiocewnqsjrkimhovimghixqryqgzhgbakpncwupcadwvglmupbexijimonxdowqsjinqzytkooacwkchatuwpsoxwvgrrejkukcvyzbkfnzfvrthmtfvmbppkdebswfpspxnelhqnjlgntqzsprmhcnuomrvuyolvzlni

the output of final would be

[['o', 12], ['m', 11], ['w', 11], ['n', 11], ['t', 9], ['v', 9], ['i', 9], ['p', 9], ['s', 8], ['z', 8], ['r', 8], ['b', 8], ['g', 8], ['k', 8], ['y', 7], ['c', 7], ['q', 7], ['h', 7], ['a', 6], ['j', 6], ['u', 6], ['d', 5], ['f', 5], ['e', 5], ['x', 5], ['l', 5]

so, the most occurring characters are

['o', 12], ['m', 11], ['w', 11], ['n', 11]

instead of

['o', 12], ['m', 11], ['n', 11], ['w', 11]

and since "m", "w" and "n" occurred equal times how do I sort the first element alphabetically while having the second element reversely sorted

2 Answers 2

1

you need to specify multiple conditions for the sort

final= Sorted(b, key = lambda e: (-e[1], e[0]))

The negative sign here makes larger numbers first (as if we are sorting in reverse order)

Sign up to request clarification or add additional context in comments.

2 Comments

Hey ahmed, thanks for replying, but this wouldn't sort it the way I wanted it to be since it'd sort alphabetically but not reversely by occurrence
It depends on what you write first in the lambda expression. If you make e[0] before e[1] it will make it alphabetically first then occurrence . If you make it as what i made it in the answer, it will sort it by occurrence first then alphabetically
0

Since pythons sort is stable you could do two sort passes:

b.sort(key=lambda x: x[0])
b.sort(key=lambda x: x[1], reverse=True)

1 Comment

Thank you I tried Ahmed's answer and It worked, and your answer worked aswell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.