Advertisement
KChrisC

Python Lambda Used to Create Jump Table

May 20th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 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.  
  33.             # Lambda in a 'jump tabel' for actually referencing a lambda func in a list
  34.     print(">>>Using lambda funcs from a list, a 'jump table'<<<")
  35.     print(">>>I.e. you can select an expression from a list based on some criteria. Cool!<<<") %()
  36.     print("Create expression list and reference and use based on list index value")
  37.     k_LambdaTest = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4]
  38.     print("Here we cycle thru each lambda in the list and print results")
  39.     for i in range(len(k_LambdaTest)): ## Uses length of lambda object to set up iteration
  40.         print("Lambda func %i is %i") %(i, k_LambdaTest[i](3)) ## Cycles thru each lambda func with 3 and prints result
  41.     print("Here we only ref the first lambda in list and print results.")
  42.     print("First lambda func result is: %i") %k_LambdaTest[0](3) ## Calls the first lambda func in list with 3
  43.     print
  44.  
  45. #------------------------------
  46.  
  47.     # Functions #
  48.         # Normal Functions
  49.            
  50.         # Generator Functions
  51.  
  52.         # Lambda Functions
  53.  
  54.     # Classes #
  55.  
  56.     # Main Loop #
  57. if __name__ == '__main__':
  58.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement