Finding the most frequent character in a string

前端 未结 10 1893
执笔经年
执笔经年 2020-12-03 21:54

I found this programming problem while looking at a job posting on SO. I thought it was pretty interesting and as a beginner Python programmer I attempted to tackle it. Howe

相关标签:
10条回答
  • 2020-12-03 22:31

    Question : Most frequent character in a string The maximum occurring character in an input string

    Method 1 :

    a = "GiniGinaProtijayi"
    
    d ={}
    chh = ''
    max = 0 
    for ch in a : d[ch] = d.get(ch,0) +1 
    for val in sorted(d.items(),reverse=True , key = lambda ch : ch[1]):
        chh = ch
        max  = d.get(ch)
    
    
    print(chh)  
    print(max)  
    

    Method 2 :

    a = "GiniGinaProtijayi"
    
    max = 0 
    chh = ''
    count = [0] * 256 
    for ch in a : count[ord(ch)] += 1
    for ch in a :
        if(count[ord(ch)] > max):
            max = count[ord(ch)] 
            chh = ch
    
    print(chh)        
    

    Method 3 :

    import collections
    
    a = "GiniGinaProtijayi"
    
    aa = collections.Counter(a).most_common(1)[0]
    print(aa)
    
    0 讨论(0)
  • 2020-12-03 22:31
    def most_frequent(text):
        frequencies = [(c, text.count(c)) for c in set(text)]
        return max(frequencies, key=lambda x: x[1])[0]
    
    s = 'ABBCCCDDDD'
    print(most_frequent(s))
    

    frequencies is a list of tuples that count the characters as (character, count). We apply max to the tuples using count's and return that tuple's character. In the event of a tie, this solution will pick only one.

    0 讨论(0)
  • 2020-12-03 22:33

    I noticed that most of the answers only come back with one item even if there is an equal amount of characters most commonly used. For example "iii 444 yyy 999". There are an equal amount of spaces, i's, 4's, y's, and 9's. The solution should come back with everything, not just the letter i:

    sentence = "iii 444 yyy 999"
    
    # Returns the first items value in the list of tuples (i.e) the largest number
    # from Counter().most_common()
    largest_count: int = Counter(sentence).most_common()[0][1]
    
    # If the tuples value is equal to the largest value, append it to the list
    most_common_list: list = [(x, y)
                             for x, y in Counter(sentence).items() if y == largest_count]
    
    print(most_common_count)
    
    # RETURNS
    [('i', 3), (' ', 3), ('4', 3), ('y', 3), ('9', 3)]
    
    0 讨论(0)
  • 2020-12-03 22:35

    If you are using Python 2.7, you can quickly do this by using collections module. collections is a hight performance data structures module. Read more at http://docs.python.org/library/collections.html#counter-objects

    >>> from collections import Counter
    >>> x = Counter("balloon")
    >>> x
    Counter({'o': 2, 'a': 1, 'b': 1, 'l': 2, 'n': 1})
    >>> x['o']
    2
    
    0 讨论(0)
提交回复
热议问题