Finding the most frequent character in a string

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

    There are many ways to do this shorter. For example, you can use the Counter class (in Python 2.7 or later):

    import collections
    s = "helloworld"
    print(collections.Counter(s).most_common(1)[0])
    

    If you don't have that, you can do the tally manually (2.5 or later has defaultdict):

    d = collections.defaultdict(int)
    for c in s:
        d[c] += 1
    print(sorted(d.items(), key=lambda x: x[1], reverse=True)[0])
    

    Having said that, there's nothing too terribly wrong with your implementation.

提交回复
热议问题