Finding the most frequent character in a string

前端 未结 10 1926
执笔经年
执笔经年 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

    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.

提交回复
热议问题