Sort by

recency

|

1256 Discussions

|

  • + 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}")
    
  • + 1 comment

    Does anyone know why i keep getting this wrong:

    import math import os import random import re import sys

    words = {}

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

    for x in range(len(s) - 1, -1, -1):
        if s[x] not in words:
            words[s[x]] = 1
        else:
            words[s[x]] += 1
    
    # Sort the dictionary by frequency (ascending)
    fixed = sorted(words.items(), key=lambda item: item[1])
    
    # Display the sorted results
    for char, freq in fixed:
        print(f"{char} {freq}")
    
  • + 0 comments
    from collections import Counter
    
    if __name__ == '__main__':
        s = input()
        d = (sorted(Counter(s).items(), key=lambda item: (-item[1], item[0]))[:3])
        
        for item in d:    
            print(item[0], item[1])
    
  • + 0 comments

    As a one-liner (with one import: from collections import Counter):

    print('\n'.join(f'{k} {v}' for k, v in Counter(sorted(input())).most_common(3)))