Last active
February 19, 2020 00:35
-
-
Save acatejr/e075147be8a373711926099f7d55813a to your computer and use it in GitHub Desktop.
Replacing For Loops in Python with Map, Filter and Reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
numbers = [1,2,3,4,5,6] | |
odd_numbers = [] | |
squared_odd_numbers = [] | |
total = 0 | |
# filter for odd numbers | |
for number in numbers: | |
if number % 2 == 1: | |
odd_numbers.append(number) | |
# square all odd numbers | |
for number in odd_numbers: | |
squared_odd_numbers.append(number * number) | |
# calculate total | |
for number in squared_odd_numbers: | |
total += number | |
# calculate average | |
""" | |
from functools import reduce | |
numbers = [1,2,3,4,5,6] | |
odd_numbers = filter(lambda n: n % 2 == 1, numbers) | |
squared_odd_numbers = map(lambda n: n * n, odd_numbers) | |
total = reduce(lambda acc, n: acc + n, squared_odd_numbers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment