Thursday, 7 July 2016

Dictionary as a set of counters in Python

An implementation is a way of doing a computation, some of the implementations are better in python than others. Let us take an example, an advantage of the dictionary implementation is that we don't have to know which letters is appearing in the string and we only have to make room for the letters that do appear and rest will happen automatically.

Here is the small example

word=”diabolical”
d=dict()
fori in word:
ifi not in d:
d[i]=1
else:
d[i]=d[i]+1
print d

The for loop traverses the string. Each time through the loop, if the character i is not in present in the dictionary, we create a new item with key i and the initial value 1 (since we’ve seen this letter once). If i is already present in the dictionary we’ve increment d[i].
Here's the output of the program:

{'a': 2, 'b': 1,'c':1,'d':1,'i':2,'l':2,'o': 1}

Learn more about to python. For furthermore information update about python and other technology you can get in touch with Softcrayons' Blog.  Softcrayons is one of the leading python training institute in India. To get more updates, news, and experience about java technology; keep update with our blog.

No comments:

Post a Comment