lfalanga
12/22/2019 - 2:41 AM

Funtional programming in Python

# Example 1: Anonymous function
"""
NOTE:
One of the more powerful aspects of Python is that it allows for a style of 
programming called functional programming, which means that you’re allowed to 
pass functions around just as if they were variables or values. Sometimes we 
take this for granted, but not all languages allow this!
Lambdas are useful when you need a quick function to do some work for you.

For example:
lambda x: x % 3 == 0

Is the same as:
def by_three(x):
  return x % 3 == 0
"""
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
# => [0, 3, 6, 9, 12, 15]

# Example 2: Using lambda, just another example
languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python", languages)
# => ['Python']

squares = [x ** 2 for x in range(1, 11)]
print filter(lambda x: x >= 30 and x <= 70, squares)  # CodeCademy version
# => [36, 49, 64]
print filter(lambda x: 30 <= x <= 70, squares)  # My version
# => [36, 49, 64]