DATA STRUCTURES:
Examples:
1.
2. Count the number for word in the file
3. Common letters in the directory
4. Set Operations on the counter
Python includes several standard programming data structures, such as list, tuple,
dict, and set, as part of its built-in types
The collections module includes implementations of several data structures
that extend those found in other modules. For example, Deque is a double-ended queue
that allows the addition or removal of items from either end. The defaultdict is a
dictionary that responds with a default value if a key is missing, while OrderedDict
remembers the sequence in which items are added to it. And namedtuple extends the
normal tuple to give each member item an attribute name in addition to a numeric
index.
collections—Container Data Types:
The collections module includes container data types beyond the built-in types
list, dict, and tuple.
Counter
A Counter is a container that tracks how many times equivalent values are added.
Initializing
Counter supports three forms of initialization. Its constructor can be called with a
sequence of items, a dictionary containing keys and counts, or using keyword arguments
mapping string names to counts.
Examples:
1.
1 2 3 4 5 6 7 | import collections c = collections.Counter() print "Initial :",c c.update('abcdaab') print "Sequence:",c c.update({'a':10,'d':5}) print "Dict :",c |
1 2 3 4 5 | >>> Initial : Counter() Sequence: Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1}) Dict : Counter({'a': 13, 'd': 6, 'b': 2, 'c': 1}) >>> |
2. Count the number for word in the file
1 2 3 4 5 6 7 8 9 10 11 | def read_count_word(): fd=open("input_test.txt",'r') word_cout=0 digit_count=0 import collections c=collections.Counter() for each_line in fd.readlines(): each_word=each_line.split() c.update(each_word) print "How many Words and count :" print c |
3. Common letters in the directory
1 2 3 4 5 6 7 8 | import collections c = collections.Counter() with open('C:\Users\ifocus\Downloads\Shashi_python', 'rt') as f: for line in f: c.update(line.rstrip().lower()) print 'Most common:' for letter, count in c.most_common(3): print '%s: %7d' % (letter, count) |
4. Set Operations on the counter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def couter_set_opertaion(): import collections c1 = collections.Counter(['a','a','b','c','a','d']) c2 = collections.Counter('alphabet') print 'C1:', c1 print 'C2:', c2 print "\nCombined counts:" print c1 + c2 print "\nSubtraction:" print c1 - c2 print '\nIntersection (taking positive minimums):' print c1 & c2 print '\nUnion (taking maximums):' print c1 | c2 |
No comments:
Post a Comment