Skip to content


Python: Newbie Code for String Histogram

Well, I have been pretty lazy about blogging lately, so pardon the amateurish code. But well, ever since no_mind egged me on to learn python, I have been learning it. Just finished a few code samples and this looked nice. It actually generates a histogram of the number of occurences of characters in a string.

#! /usr/bin/env python

#python program to input a number and generate a histogram of the characters in it
import string
txt=raw_input()
txtarray=list(string.lower(txt))
chardict={}
for char in txtarray:
    if chardict.has_key(char):
        chardict[char]=chardict[char]+1
    else:
        chardict[char]=1
charlistpair=chardict.items()
charlistpair.sort()
for pair in charlistpair:
    print pair[0], “\t”,
    for i in range(0, pair[1]):
        print “|”,
    print

  

Posted in Tutorial.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.