Finding the most frequent character in a string

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

提交回复
热议问题