Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Last active Jul 5, 2020
Embed
What would you like to do?
import itertools
#using add and mul operator,so importing operator module
import operator
#using reduce(),so importing reduce() from functools module
from functools import reduce
#If func parameter is not mentioned,by default it will perform addition operation)
l1=itertools.accumulate([1,2,3,4,5])
print (l1)#Output:<itertools.accumulate object at 0x02CD94C8>
#Converting iterator to list object.
print (list(l1))#Output:[1, 3, 6, 10, 15]
#using reduce() for same function
r1=reduce(operator.add,[1,2,3,4,5])
print (r1)#Output:15
#If initial parameter is mentioned, it will start accumulating from the initial value.
#It will contain more than one element in the ouptut iterable.
l2=itertools.accumulate([1,2,3,4,5],operator.add,initial=10)
print (list(l2))#Output:[10, 11, 13, 16, 20, 25]
#it takes operator mul as function
# It will perform multiplication on first two elements, then it will perform multiplication of next two element in the iterable.
l3=itertools.accumulate([1,2,3,5,5],operator.mul)
print (list(l3))#Output:[1, 2, 6, 30, 150]
#using reduce() for same function mul.
r2=reduce(operator.mul,[1,2,3,4,5])
print (r2)#Output:120
l4=itertools.accumulate([2,4,6,3,1],max)
print (list(l4))#Output:[2, 4, 6, 6, 6]
#using reduce for same function max
r3=reduce(max,[2,4,6,3,1])
print (r3)#Output:6
#It takes min function as parameter.
# It will compare two elements and find the minimum element,then compare the other elements and find the mininum element.
l5=itertools.accumulate([2,4,6,3,1],min)
print (list(l5))#Output:[2, 2, 2, 2, 1]
#using reduce() for same function min
r4=reduce(min,[2,4,6,3,1])
print (r4)#Output:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment