Dictionary - Histogram - character frequency of a string

 # Dictionary - Histograms

# Create a histogram based on the frequency of characters in given string

# Histogram - String - Word Frequency


import operator


string1 = "An algorithm is a step-by-step procedure to solve a given problem. It is a well-defined computational procedure that takes some values as input, manipulates them using a set of instructions and produces some values as output and terminates in a finite amount of time. An algorithm, when formally written in a programming language is called a program, or code. Derivation of an algorithm that solves the problem and conversion of the algorithm into code, together,  is known as Algorithmic Problem Solving."


string1 = string1.lower()


ch = set(string1)


D = {c:string1.count(c) for c in ch if c.isalpha()}  


print("Histogram")

print("Length of dictionary = ", len(D))

print(D)


DSorted = sorted(D.items(), key=operator.itemgetter(1), reverse=True)


D_max3 = dict(DSorted[:3])

print("Most frequently used 3 characters:")

print(D_max3)


"""

Sample output

>python Dict_Hist.py

Histogram

Length of dictionary =  22

{'t': 37, 'a': 39, 'w': 4, 'l': 22, 'g': 14, 'h': 12, 'o': 38, 'u': 14, 's': 26, 'i': 32, 'm': 20, 'e': 40, 'd': 12, 'c': 10, 'r': 25, 'v': 8, 'n': 30, 'b': 4, 'y': 2, 'p': 14, 'k': 2, 'f': 7}

Most frequently used 3 characters:

{'e': 40, 'a': 39, 'o': 38}

"""

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu