How to find the second most frequent character in a string with Python

2 Answers

0 votes
def GetSecondMostFrequentChar(str) :
    count = [0] * 256  # 256 = ASCII table size
 
    for i in range(len(str)) :
        count[ord(str[i])] += 1
 
    first, second = 0, 0
 
    for i in range(256) :
        if count[i] > count[first] :
            second = first
            first = i
        elif (count[i] > count[second] and count[i] != count[first] ) :
            second = i

    return chr(second)
 

s = "bbaddddccce"
     
print(GetSecondMostFrequentChar(s))



'''
run:

c

'''

 



answered Aug 31, 2022 by avibootz
0 votes
import collections
  
string = "bbaddddccce"

ddict = collections.defaultdict(int)

for ch in string:
    ddict[ch] += 1
    
print(sorted(ddict.items(), key=lambda x: x[1], reverse=True)[1])
print(sorted(ddict.items(), key=lambda x: x[1], reverse=True)[1][0])

 
 
'''
run:
 
('c', 3)
c
 
'''

 



answered Nov 29, 2024 by avibootz
...