Sort by

recency

|

1259 Discussions

|

  • + 0 comments

    Is better solution using Counter (as i learnt from other posting), anyway here is my solution.

    from itertools import groupby

    if name == 'main':

    s = sorted(list(input()))
    
    cap= [(k, len(list(g))) for k, g in groupby(s) ]
    
    print (cap)
    res = sorted(cap, reverse=True, key=lambda qty: qty[1])
    

    for x in range(3):
    print(res[x][0],res[x][1] )

  • + 0 comments
    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    from collections import Counter
    
    if __name__ == '__main__':
        s = input()  # Get the input string
        
        # Count the frequency of each character
        counter = Counter(s)
        
        # Sort by frequency in descending order and by character in ascending order
        most_common = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
        
        # Print the top 3 most common characters
        for i in range(3):
            char, count = most_common[i]
            print(char, count)
    
  • + 0 comments

    All TestCases Passed

    from collections import Counter
    
    if __name__ == '__main__':
        s = input().strip()
        # Count the occurrences of each character
        count = Counter(s)
        # Sort by frequency (descending) and then alphabetically for ties
        sorted_count = sorted(count.items(), key=lambda x: (-x[1], x[0]))
        # Print the top three characters
        for char, freq in sorted_count[:3]:
            print(char, freq)
    
  • + 0 comments

    fixed: words = {}

    if name == 'main': s = input()

    # Count character frequencies
    for char in s:
        if char not in words:
            words[char] = 1
        else:
            words[char] += 1
    
    fixed = sorted(words.items(), key=lambda item: (-item[1], item[0]))
    
    
    for i, (char, freq) in enumerate(fixed):
        if i >= 3:  # Stop after printing the top 3
            break
        print(f"{char} {freq}")
    
  • + 0 comments

    I have just started learning and I was not aware of Counter Class and the method most_common()

    Glad I came accross Boki's solution from 9 years back! Classes are a bit tough to understand though so I made something of my own.

    from collections import Counter
    
    
    if __name__ == '__main__':
        
        # sorting alphabetically so they occur in alphabetic order
        company_name = sorted(input())
        
        # count 3 most common characters
        three_most_common_chars = Counter(company_name).most_common(3)
        
        for char, freq in three_most_common_chars:
            print(f"{char} {freq}")
        
        for char, freq in three_most_common_chars:
            print(f"{char} {freq}")