Check character frequency in Python

#!/usr/bin/python

“””
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”).
“””

def charf(x):
    dit={‘a’:0, ‘b’:0,’c’:0,’d’:0,’e’:0,’f’:0,’g’:0,’h’:0,’i’:0,’j’:0,’k’:0,’l’:0,’m’:0,’n’:0,’o’:0,’p’:0,’q’:0,’r’:0,’s’:0,’t’:0,’u’:0,’v’:0,’w’:0,’x’:0,’y’:0,’z’:0}
    a = list(x)
    c = len(a)
    for i in range(0,c):
        for key,value in dit.items():
            if a[i] == key:
                dit[key] += 1
    print dit
        
def main():
    charf(“abbabcbdbabdbdbabababcbcbab”)

if __name__ == ‘__main__’:
    main()

Advertisements

Leave a comment

Filed under Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s