Home > Net >  functional programming in python - using map(), filter(), and sum() together - java .stream() equiva
functional programming in python - using map(), filter(), and sum() together - java .stream() equiva

Time:01-31

I'm learning about functional programming in Python and Java.

I've got some Java code that finds out the sum of double of even numbers from a list.

I'd like to use functional programming in Python to do the same thing (ie find the sum of double of even numbers from the list). What is good practice in terms of using filter(), map(), and sum() together and for the code to be readable?

What I've written in Python (see below) does the job but isn't very readable.

Thanks for any help!

# JAVA

import java.util.Arrays;
import java.util.List;
public class GFG {
    public static void main(String[] args)
    {
        List<Integer> numbers
            = Arrays.asList(11, 22, 33, 44,
                            55, 66, 77, 88,
                            99, 100);
 
        System.out.println(
            numbers.stream()
                .filter(number -> number % 2 == 0)
                .mapToInt(e -> e * 2)
                .sum());
    }
}

// OUTPUT: 640 

# PYTHON 

class GFG:

    @staticmethod
    def main():
        numbers = [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
        print(sum(map(lambda x: x * 2, (filter(lambda x: x % 2 == 0, numbers)))))
   

GFG.main()

# OUTPUT: 640 

CodePudding user response:

Use sum with a generator expression.

sum(x * 2 for x in numbers if x % 2 == 0)

CodePudding user response:

The reason the Python is less readable is that map, filter etc are methods in Java while they are functions in Python. This means that in Java, you can use indentation to make everything read left-to-right in a fluid style.

There is no particularly reason you can't create your own stream in Python:

class MyStream:
     def __init__(iterator):
          self.iterator = iterator

     def map(func):
          return MyStream(map(func, self.iterator))
     
     def filter(func):
          return MyStream(filter(func, self.iterator))
     ...

No one would actually do this in Python because list comprehension and generator expressions are considered much more readable.

  • Related