-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22thReduceinPython.py
More file actions
46 lines (23 loc) · 1.01 KB
/
22thReduceinPython.py
File metadata and controls
46 lines (23 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# ! Reduce Function
# * Used to make an iterable into 1 value
# * Part of functools module
# * Syntax: reduce(function, iterable[,initializer])
# * function must take 2 arguments as first argument is accumalated value and second is another element of the iterable
# * iterable is any iterable
# * initializer is used to as the first thing to add, subtract or multiply the iterable[0]
# * e.g
import functools
a = [11, 22, 33, 44, 55]
r = functools.reduce(lambda x,y: x * y, a, 100) # * 100 is an initializer i.e. It is multiplied to the first element and then each element is multiplied to each other
print(r)
r = functools.reduce(lambda x,y: x * y, a)
print(r)
# * Finding Factorial
n = 5
print('Finding Factorial using reduce():',functools.reduce(int.__mul__, range(1, n + 1)))
# * Finding sum till n
n = 10
print('Adding all elements in the list:',functools.reduce(int.__add__, range(n)))
# * To find max element
a = [11, 22, 33, 44, 55]
print('Max no.:',functools.reduce(lambda x,y: x if x > y else y, a))