Created
November 29, 2015 20:50
-
-
Save GitMoIO/7f2abd7e4887c15993f5 to your computer and use it in GitHub Desktop.
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
#lambda | |
#lambda parameter: expression | |
f = lambda x, y: x + y | |
f(15,1) | |
#=> 16 | |
#using within a high order function | |
def my_function(x): | |
return lambda arr: [x * each for each in arr] | |
fives = my_function(5) | |
print fives([1,2,3,4]) | |
#=>[5,10,15,20] | |
##################### | |
#map() | |
#r= map(func, seq) | |
def my_function(x): | |
return x**2 | |
r = map(my_function,[1,2,3,4,5]) #map function to elemement of a sequence i.e list | |
#returns a new list | |
print r | |
#=> [1,4,9,16,25] | |
#Example 2: | |
def fahrenheit(T): | |
return ((float(9)/5)*T + 32) | |
def celsius(T): | |
return (float(5)/9)*(T-32) | |
temp = (36.5, 37, 37.5, 39) | |
F= map(fahrenheit, temp) | |
C= map(celsius, F) | |
#Another way of coding the above formulas is using lambda with map() | |
#A perfect use case for lambda, a throw away function that we won't need beyond this | |
Celsius = [39.2, 36.5, 37.3, 37.8] | |
Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) | |
print Fahrenheit | |
[102.56, 97.700000000000003, 99.140000000000001, 100.03999999999999] | |
C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit) | |
print C | |
[39.200000000000003, 36.5, 37.300000000000004, 37.799999999999997] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment