The Startup
Published in

The Startup

Functional Programming: Reduce() Function in Python

Reducing sequence to a single output value!

Photo by Markus Spiske on Unsplash

Working with reduce() function

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
[Output]: 15
got_chars=(
got_char("name":"John","profession":"King's Hand","experience_in_year":3),
got_char("name":"Arya Stark","profession":"No One","experience_in_year":4),
got_char("name":"Sansa Stark","profession":"Queen Winterfell","experience_in_year":1),
got_char("name":"Danaerys","profession":"Queen","experience_in_year":3)
)
reduce(lambda acc, char: acc+char, got_chars)/len(got_chars)
[Output]: 2.2
reduce(lambda acc, char: acc+char, got_chars,0)/len(got_chars)
[Output]: 2.2

Grouping values using reduce()

got_chars=(
got_char("name":"John","profession":"King's Hand","experience_in_year":3, "sex":"M"),
got_char("name":"Arya Stark","profession":"No One","experience_in_year":4, "sex":"F"),
got_char("name":"Sansa Stark","profession":"Queen Winterfell","experience_in_year":1, "sex":"F"),
got_char("name":"Danaerys","profession":"Queen","experience_in_year":3, "sex":"F")
)
def reduce_fun(acc,char):
acc[char.sex].append[char.name]
return acc
reduce(reduce_fun, got_chars, {'M':[],'F':[]})
[Output]: {'M': ['John'],
'F': ['Arya Stark', 'Sansa Stark', 'Danaerys']}
{'M':[],'F':[]}
from collections import defaultdict
reduce(reduce_fun, got_chars, defaultdict([list]))
defaultdict(<class 'list' >,
{'M': ['John'],
'F': ['Arya Stark', 'Sansa Stark', 'Danaerys']})

Summary

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store