count how many times each letter appears

Q) Suppose you are given a string and you want to count how many times each letter appears:

Well you build empty dictionary parse sequence of string check if character exist or not in dictionary if it's not then count it =1 if it's exist count+1



def histogram(string):
    my_dictionary = dict()
    for character in string:
        if character not in my_dictionary:
            my_dictionary[character] = 1
        else:
            my_dictionary[character] += 1
    return my_dictionary
user_string = raw_input("Enter your string: ")
print histogram(user_string)


That's it :)

Comments

Popular Posts