Monday, January 30, 2017

Character Frequency In a String Python

Tags

Question::

Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").

Code::

def char_freq(l):
    d={}
    for i in (range(len(l))):
        if (l[i] in d):
            d[l[i]]=int(d.get(l[i]))+1
        else:
            d[l[i]]=1     
    return d
nt=input("Enter any String:")
n=char_freq(nt)

print(n)

Output::