Skip to main content

Streamlining Code: The Power of Map, Filter, and Reduce in Functional Programming - Python



Map, Filter, and Reduce are key paradigms in functional programming. 
They enable the creation of concise and efficient code, reducing the need for explicit loops and branching. 

1MAP:

Map applies a function to all items in an input list.

 

# Example: Converting temperatures from Celsius to Fahrenheit

celsius = [010203040]

fahrenheit = list(map(lambda c: (c * 9/5+ 32celsius))

print(fahrenheit)  

# Output: [32.0, 50.0, 68.0, 86.0, 104.0]

 

In data science, you might use map to apply a transformation to each element in a dataset.

 

2FILTER:

Filter creates a list of elements for which a function returns true.

 

# Example: Filtering out even numbers

numbers = [12345678910]

odd_numbers = list(filter(lambda xx % 2 != 0numbers))

print(odd_numbers)  

# Output: [1, 3, 5, 7, 9]

 

In data analysis, you could use filter to select data points that meet certain criteria.

 

3REDUCE:

Reduce applies a rolling computation to sequential pairs of values in a list.

 

from functools import reduce

 

# Example: Calculating the product of all numbers in a list

numbers = [12345]

product = reduce(lambda xyx * ynumbers)

print(product)  

# Output: 120

 

In data science, reduce can be used for aggregations like sum, product, or more complex rolling computations.

 

Here's a more data science-oriented example combining all three:

 

import pandas as pd

from functools

 

# Sample dataset

data = pd.DataFrame({

    'name': ['Alice''Bob''Charlie''David''Eve'],

    'age': [2530354045],

    'salary': [50000600007500090000100000]

})

 

# MAP: Increase all salaries by 10%

data['new_salary'] = list(map(lambda xx * 1.1data['salary']))

 

# FILTER: Select employees older than 30

older_employees = list(filter(lambda rowrow['age'> 30data.to_dict('records')))

 

# REDUCE: Calculate total salary of older employees

total_salary = functools.reduce(lambda xyx + y['new_salary'], older_employees0)

 

print(data)

print("\nOlder employees:\n"older_employees)

print("\nTotal salary of older employees:\n"total_salary)


# Output:

      name  age  salary  new_salary

0    Alice   25   50000     55000.0

1      Bob   30   60000     66000.0

2  Charlie   35   75000     82500.0

3    David   40   90000     99000.0

4      Eve   45  100000    110000.0


Older employees:

 [{'name': 'Charlie', 'age': 35, 'salary': 75000, 'new_salary': 82500.0}, {'name': 'David', 'age': 40, 'salary': 90000, 'new_salary': 99000.00000000001}, {'name': 'Eve', 'age': 45, 'salary': 100000, 'new_salary': 110000.00000000001}]


Total salary of older employees:

 291500.0

 

This example demonstrates:

- Using MAP to apply a salary increase

- Using FILTER to select older employees

- Using REDUCE to calculate the total salary of filtered employees

 

These functions can significantly simplify data manipulation tasks and are often more readable and efficient than traditional for loops.

 

Happy Computing!

Comments

Popular posts from this blog

The Git Life: Your Guide to Seamless Collaboration and Control

A Comprehensive Guide to Git: From Basics to Advanced   What is Git and GitHub?   Imagine you are organizing a wedding —a grand celebration with many family members, friends, and vendors involved. You need a foolproof way to manage tasks, keep track of who is doing what, and ensure that everyone stays on the same page. This is where Git and GitHub come in, though in the world of technology.   What is Git?   Git is like the wedding planner or the master ledger for managing all wedding-related activities. Think of it as a system that helps you:      1.   Keep track of every change made (like noting down who ordered the flowers or printed the invitation cards).       2.   Maintain a record of what changes happened and who made them (e.g., the uncle who updated the guest list).       3.   Go back to an earlier version if something goes wrong (...

How to Open Jupyter Lab in your favourite browser other than system default browser in Mac OS: A Step-by-Step Guide

Are you tired of Jupyter Lab opening in your default browser? Would you prefer to use Google Chrome or another browser of your choice? This guide will walk you through the process of configuring Jupyter Lab to open in your preferred browser, with a focus on using Google Chrome. The Challenge   Many tutorials suggest using the command prompt to modify Jupyter's configuration. However, this method often results in zsh errors and permission issues, even when the necessary permissions seem to be in place. This guide offers a more reliable solution that has proven successful for many users.   Step-by-Step Solution   1. Locate the Configuration File - Open Finder and navigate to your user folder (typically named after your username). - Use the keyboard shortcut Command + Shift + . (full stop) to reveal hidden folders. - Look for a hidden folder named .jupyter . - Within this folder, you'll find the jupyter_notebook_config.py file.   2. Edit the Configuration File - Open ...

Streamlit - An interactive app guide for Data Scientists and ML Engineers

Streamlit: A Guide to Create an Interactive App Introduction to Streamlit:   What is Streamlit? Streamlit  is an open-source Python library that allows you to build interactive and data-driven web applications with minimal effort. It is widely used in data science, machine learning, and analytics to create quick and interactive dashboards without requiring web development knowledge.   Why to use Streamlit? •                  Easy to use: No front-end knowledge required. •                  Quick development: Turn Python scripts into web apps instantly. •                  Interactive widgets: Built-in support for user interaction. •                  Ideal for ...