Tuesday, December 15, 2015

Python Data Structures Collections Deque

Deque
A double-ended queue, or deque, supports adding and removing elements from either
end. The more commonly used structures, stacks, and queues

Example:
1
2
3
4
5
6
7
8
9
def deque_example():
    import collections
    d = collections.deque('abcdefg')
    print 'Deque:', d
    print 'Length:', len(d)
    print 'Left end:', d[0]
    print 'Right end:', d[-1]
    d.remove('c')
    print 'remove(c):', d
Output:
1
2
3
4
5
6
7
output:
$ python collections_deque.py
Deque: deque('a', 'b', 'c', 'd', 'e', 'f', 'g'])
Length: 7
Left end: a
Right end: g
remove(c): deque([a, b, d, e, f, g])

Populating
A deque can be populated from either end, termed “left” and “right” in the Python
implementation.

Example:

1
2
3
4
5
6
7
output:
$ python collections_deque.py
Deque: deque([a, b, c, d, e, f, g])
Length: 7
Left end: a
Right end: g
remove(c): deque([a, b, d, e, f, g])
Output:
1
2
3
4
5
$ python collections_deque_populating.py
extend : deque([a, b, c, d, e, f, g])
append : deque([a, b, c, d, e, f, g, h])
extendleft: deque([5, 4, 3, 2, 1, 0])
appendleft: deque([6, 5, 4, 3, 2, 1, 0])

Consuming
Similarly, the elements of the deque can be consumed from both ends or either end,
depending on the algorithm being applied

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def deque_consume():
    import collections
    print 'From the right:'
    d = collections.deque('abcdefg')
    while True:
        try:
            print d.pop()
        except IndexError:
            break
    print
    print '\nFrom the left:'
    d = collections.deque(xrange(6))
    while True:
        try:
            print d.popleft()
        except IndexError:
            break
    print

deque_comsume()

Output:
1
2
3
4
5
$ python collections_deque_consuming.py
From the right:
g f e d c b a
From the left:
0 1 2 3 4 5

Rotating
Another useful capability of the deque is to rotate it in either direction, to skip over
some items.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def deque_rotate():
    import collections
    d = collections.deque(xrange(10))
    print 'Normal :', d
    d = collections.deque(xrange(10))
    d.rotate(2)
    print 'Right rotation:', d
    d = collections.deque(xrange(10))
    d.rotate(-2)
    print 'Left rotation :', d

deque_rotate()

Monday, December 14, 2015

Python Data Structures Collections

DATA STRUCTURES:
                   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