Featured Post

Keyword to create root window in python

What are collections and itertools in python - part 2


 

(6)COLLECTIONS: 


Collections is a python module that has 5 different types.

1.Counter:

counter is container that stores the dictionary keys.

for example: 

from collections import Counter 
= "aaaaabbbbccc"
my_counter = Counter(a)
print(my_counter)

output = Counter({'a':5,'b':4, 'c':3})


To print the most common elements in the dictionay use 'most_common'.

for example:

from collections import Counter 
= "aaaaabbbbccc"
my_counter = Counter(a)
print(my_counter)
print(my_counter.most_common(1))

output = Counter({'a':5,'b':4, 'c':3})

[('a', 5)]


for example :

from collections import Counter 
= "aaaaabbbbccc"
my_counter = Counter(a)
print(my_counter)
print(my_counter.most_common(1)[0][0])

output =  Counter({'a':5,'b':4, 'c':3})

  a 


To convert the dictionary to a list use 'list'.

for example: 

from collections import Counter 
= "aaaaabbbbccc"
my_counter = Counter(a)
print(my_counter)
print(list(my_counter.elements()))

output = Counter({'a': 5, 'b': 4, 'c': 3})

['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']


2.Namedtuple: 

To store values

for example:

from collections import namedtuple
Point = namedtuple('Point','x,y')
pt = Point(1,4)
print(pt)

output = Point(x=1, y=4)


3.OrderedDict:

OrderedDict is just a dictionary which remembers a order.

for example:

from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['a'= 1
ordered_dict['b'= 2
ordered_dict['c'= 3
ordered_dict['d'= 4
print(ordered_dict)

output = OrderedDict([('a', 1), ('b', 2), ('c',3), ('d', 4)])


4.Defaultdict:

The defaultdict is a container that's similar to the usual dict container, but the only difference is that a defaultdict will have a default value if that key has not been set yet.

for example:

from collections import defaultdict

# initialize with a default integer value, i.e 0
= defaultdict(int)
d['yellow'= 1
d['blue'= 2
print(d.items())
print(d['green'])

output = dict_items([('yellow', 1), ('blue', 2)])

0


5.Deque:

Used to add or remove the elements.

for example:  

from collections import deque 
= deque()
d.append(1)
d.append(2)
print(d)

output = deque([1,2])

To remove the element from the list use 'appendleft'

for example:

from collections import deque
= deque()

# append() : add elements to the right end 
d.append('a')
d.append('b')
print(d)

# appendleft() : add elements to the left end 
d.appendleft('c')
print(d)

# pop() : return and remove elements from the right
print(d.pop())
print(d)

# popleft() : return and remove elements from the left
print(d.popleft())
print(d)

# clear() : remove all elements
d.clear()
print(d)

= deque(['a''b''c''d'])

# extend at right or left side
d.extend(['e''f''g'])
d.extendleft(['h''i''j']) # note that 'j' is now at the left most position
print(d)

# count(x) : returns the number of found elements
print(d.count('h'))

# rotate 1 positions to the right
d.rotate(1)
print(d)

# rotate 2 positions to the left
d.rotate(-2)
print(d)

output = 

deque(['a', 'b'])

deque(['c', 'a', 'b'])

b

deque(['c', 'a'])

c

deque(['a'])

deque([])

deque(['j', 'i', 'h', 'a', 'b', 'c', 'd', 'e', 'f', 'g'])

1

deque(['g', 'j', 'i', 'h', 'a', 'b', 'c', 'd', 'e', 'f'])

deque(['i', 'h', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'j'])

 (7)ITERTOOLS:

An iterator is an object that contains a countable number of values.
The Python itertools module is a collection of tools for handling iterators. Simply put, iterators are data types that can be used in a 'for loop'. The most common iterator in Python is the list.

1.Product:

combining elements from two lists.

for example:

from itertools import product
= [12]
= [34]
prod = product(a,b)
print(list(prod))

output = [(1,3), (1,4), (2,3), (2,4)]


To repeat the elements multiple times. 

for example:

from itertools import product
= [12]
= [34]
prod = product(a,b, repeat=2)
print(list(prod))

output = [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4), (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4), (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4), (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]


2.Permutstions:

Rerturning all possible orderings of the input

for example: 

from itertools import permutations
= [1,2,3]
perm = permutations(a)
print(list(perm))

output = [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]


Giving length 

for example:

from itertools import permutations
= [1,2,3]
perm = permutations(a, 2)
print(list(perm))

output = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

 

3.Combinations:

Making all possible combinations with specified length. Giving length is mandatory.

for example:

from itertools import combinations
= [1,2,3,4]
comb = combinations(a, 2)
print(list(comb))

output  =  [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


using Combinations_with_replacement

for example:

from itertools import combinations, combinations_with_replacement

# the second argument is mandatory and specifies the length of the output tuples.
comb = combinations([1234], 2)
print(list(comb))

comb = combinations_with_replacement([1234], 2)
print(list(comb))

output = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]


4.Accumulate: 

Make an iterator that returns accumulated sums or accumulated results of the binary function.

for example: 

from itertools import accumulate
= [1,2,3,4]
acc = accumulate(a)
print(a)
print(list(acc))

output = [1, 2, 3, 4]

 [1, 3, 6, 10]


To multiply.

for example: 

import operator
from itertools import accumulate
= [1,2,3,4]
acc = accumulate(a, func=operator.mul)
print(a)
print(list(acc))

output = [1, 2, 3, 4]

 [1, 2, 6, 24]


Max comparison.

for example:

import operator
from itertools import accumulate
= [1,2,3,4]
acc = accumulate(a, func=max)
print(a)
print(list(acc))

output = [1, 2, 5, 4]

         [1, 2, 5, 5]  


5.Groupby: 

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element.

for example:

from itertools import groupby 

def smaller_than_3(x):
    return x < 3

= [1234]
group_obj = groupby(a, key=smaller_than_3)

for key, value in group_obj:
    print(key, list(value))

output = True [1, 2]

 False[3, 4]


6.Infinite iterators:

Count, Cycle, Repeat

The 'Count' iterator counts after the number you enter in the count().

for example:

from itertools import count, cycle, repeat

for i in count(10):
    print(i)

output = 10

 11

 12

   13

 14....


for example:

from itertools import count, cycle, repeat

for i in count(10):
    print(i)
    if i == 15:
      break 

output = 

10

11

12

13

14

15

The iterator prints all values in sequence from the passed argument.

for example:

from itertools import count, cycle, repeat

= [123]

for i in cycle(a):
    print(i)

output = 1

   2

 3

 1

 2

 3....

This iterator prints the values repeatedly multiple times according to the passed argument.

for example:

from itertools import count, cycle, repeat

= [123]

for i in repeat(14):
    print(i)

output  = 1

  1

  1

  1

Comments