Advertisement
KChrisC

Some Python Lambda Tutorial Code

May 20th, 2014
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.52 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name:        module1
  3. # Purpose:
  4. #
  5. # Notes:       One of the major pieces of Python that lambda examples are applied to regularly are
  6. #                 Tkinter callbacks.
  7. #              Basically, Python’s lambda is a tool for building functions (or more precisely,
  8. #                 function objects). That means that Python has two tools for building functions: def and lambda.
  9. #
  10. # References:  http://www.blog.pythonlibrary.org/2010/07/19/the-python-lambda/
  11. #              http://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/
  12. #              http://www.bogotobogo.com/python/python_functions_lambda.php
  13. #
  14. # Author:      User
  15. #
  16. # Created:     17/05/2014
  17. # Copyright:   (c) User 2014
  18. # Licence:     <your licence>
  19. #-------------------------------------------------------------------------------
  20.     # Imports #
  21. import math
  22.  
  23.     # Main #
  24. def main():
  25.         # Variables
  26.             # Local
  27.  
  28.             #Global
  29.     print(">>>Best if code is viewed in PyScripter. All code is directly from the above references,\
  30.           a modification of their code or inspired by their code.<<<") %()
  31.     print
  32.     print(">>>Normal and lambda funcs comparison<<<")
  33.     for i in range(49, 65, 15): ## Loops thru two squares for test purposes
  34.         print "Using math func, root of %i is %.2f" %(i, f_sqroot(i)) ## Prints result of call to normal func
  35.         print "Using lambda func, root of %i is %.2f" %(i, k_square_rt(i)) ## Prints result of call to lambda func
  36.         print
  37.  
  38.     print ("Call to k_sum, lambda, func, is %i") %k_sum(3, 4) ## Calls lambda sum kfunc
  39.     print
  40.  
  41.             # Lambda in a 'jump tabel' for actually referencing a lambda func in a list
  42.     print(">>>Using lambda funcs from a list, a 'jump table'<<<")
  43.     print(">>>I.e. you can select an expression from a list based on some criteria. Cool!<<<") %()
  44.     print("Create expression list and reference and use based on list index value")
  45.     k_LambdaTest = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4]
  46.     print("Here we cycle thru each lambda in the list and print results")
  47.     for i in range(len(k_LambdaTest)): ## Uses length of lambda object to set up iteration
  48.         print("Lambda func %i is %i") %(i, k_LambdaTest[i](3)) ## Cycles thru each lambda func with 3 and prints result
  49.     print("Here we only ref the first lambda in list and print results.")
  50.     print("First lambda func result is: %i") %k_LambdaTest[0](3) ## Calls the first lambda func in list with 3
  51.     print
  52.  
  53.     print(">>>Use lambda to select from a list without for loop<<<")
  54.     k_Min = (lambda x, y: x if x < y else y) ## Defines lambda kfunc
  55.     print("Min is %i") %k_Min(101*99, 102*98) ## Uses kfunc to print min of list
  56.     print("Min is %i") %k_Min(102*98, 101*99) ## Uses kfunc to print min of list
  57.     print
  58.  
  59.     print(">>>Normal vs inline lambda funcs<<<")
  60.     x = 2
  61.     print("Normal cube func of %i: %i") %(x, f_Cube(x))
  62.     k_Lamb = lambda x: x ** 3
  63.     print ("Lambda cube func of %i produces: %i") %(x, k_Lamb(x))
  64.     print
  65.  
  66.             # Lambda used to modify the expression in a norm func
  67.     print(">>>Lambda being used to modify an expression in a norm func<<<")
  68.     k_ModSum = f_Make_Incrementor(2) ## Calls the norm func with the value for the lambda func expression
  69.     k_ModSum2 = f_Make_Incrementor(6) ## Calls the norm func with the value for the lambda func expression
  70.     print("First lambda useing a base of 2 (x + 2) and x of 42: %i") %(k_ModSum(42))
  71.     print("Second lambda useing a base of 6 (x + 6) and x of 42: %i") %(k_ModSum2(42))
  72.     print
  73.             # Lambda used to inline filter a list
  74.                 # Produce prime list
  75.     print(">>>Lambda being used to quickly create a 2 to 49 'sieve of Eratosthenes' prime list<<<")
  76.     v_Nums = range(2, 50) ## Range to 'sieve primes out of
  77.     for i in range(2, 8): ## Sieve range, 2 to sqrt of 49
  78.         v_Nums = filter(lambda x: x == i or x % i, v_Nums) ## Instead of having to loop thru each list item
  79.                                                          ## and filter each out with if/then, we filter inline
  80.                                                          ## with lambda
  81.     print v_Nums ## Print 2 to 49 prime list
  82.     print
  83.  
  84.                 # Produce odd list
  85.     print(">>>Lambda being used to quickly create an odds list<<<")
  86.     v_List = range(2, 50)
  87.     for i in v_List:
  88.         v_List = filter(lambda x: x % 2, v_List)
  89.     print("Odd List %s") %(v_List)
  90.     print
  91.  
  92.             # Lambda and map
  93.     print(">>>Moding a list using trad., map and func, and map and lambda<<<")
  94.                 # Traditional way to modify each item in a list
  95.     print(">>>Lambda and map<<<")
  96.     items = [1, 2, 3, 4, 5]
  97.     squared = []
  98.     for x in items:
  99.        squared.append(x ** 2)
  100.     print ("Traditional way: %s") %squared
  101.  
  102.                 # Using a traditional func and 'Map' to modify each item in a list
  103.     def f_Sqr(x): return x ** 2 ## Function
  104.     print("With func and map: %s") %list(map(f_Sqr, items))## 'Map' applies the func to each item in turn without
  105.                                                      ## explicitly using a for loop
  106.     print("With map and lambda: %s") %list(map((lambda x: x **2), items)) ## Instead of a func just put the lambda func
  107.                                                                  ## inside the map, no for loop needed
  108.  
  109.             # Tests
  110.             # Output to file
  111.     ## v_Path = 'C:/Users/User/Documents/out.txt'
  112.     ## v_Mode = 'w'
  113.     ## v_FileConn = f_OutputToFileOut(v_Path, v_Mode)
  114.  
  115.     ## sys.exit("Error message") ## Stop execution
  116.  
  117. #------------------------------
  118.  
  119.     # Functions #
  120.         # Normal Functions
  121.             # Make a modifiable func using lambda
  122. def f_Make_Incrementor(n):
  123.     return lambda x: x + n ## returns the modified by (n) lambda func
  124.  
  125.             # Cube func
  126. def f_Cube(x):
  127.     return x ** 3 ## Returns the result of  the evaluated expression
  128.  
  129.             # Square root func
  130. def f_sqroot(x): # Start func
  131.     return math.sqrt(x) ## Returns result of call to math.sqrt()
  132.  
  133.         # Generator Functions
  134. def g_TestGen():
  135.     pass
  136.  
  137.         # Lambda Functions
  138.             # Square root lambda func
  139. k_square_rt = lambda x: math.sqrt(x) ## Creates and obj, square_rt, that calls the math.sqrt() func
  140.                                    ##  def x: return math.sqrt(x)
  141.  
  142. k_sum = lambda x, y:   x + y ## def sum(x,y): return x + y
  143.  
  144.     # Classes #
  145.  
  146.     # Main Loop #
  147. if __name__ == '__main__':
  148.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement