Advertisement
Guest User

loops Vs Recur

a guest
Jun 20th, 2017
91
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.81 KB | None
  1. """
  2. Comparing the for loop to iteration for calculating the product of the numbers in an array
  3. June 2017, JM
  4. """
  5.  
  6. from time import time
  7. from sys import setrecursionlimit
  8.  
  9.  
  10. #Function Declarations:
  11. #------------------------------------------
  12.  
  13. def multiLoop(*args):
  14.     '''
  15.    returns the product of the elements in
  16.    args via iteration.
  17.    Expects all args to by numbers
  18.    '''
  19.     total = 1
  20.     for i in range(len(args)):
  21.         total *= aList[i]
  22.     return total
  23.    
  24. def multiply(*args):
  25.     '''
  26.    returns the product of the elements in
  27.    args via recursion.
  28.    Expects all args to be numbers
  29.    '''
  30.     def recursive_product(nums):
  31.         '''
  32.        Recursively updates the product of the
  33.        array nums, returns if length 1
  34.        '''
  35.         if len(nums) > 1:
  36.             return nums[0] * recursive_product(nums[1:])
  37.         else:
  38.             return nums[0]
  39.     return recursive_product(args)
  40.  
  41. def timer_func(func, arg):
  42.     '''
  43.    wrapper function for timing
  44.    other functions.
  45.    Expects a function and a single arguments
  46.    '''
  47.     start = time()
  48.     func(*arg)
  49.     stop = time()
  50.     return stop - start
  51.    
  52.  
  53. #Increase recursion limit, initiate vars:
  54. #------------------------------------------
  55.  
  56. setrecursionlimit(10003)
  57. aList = list(range(1,9999))
  58. total_loop,total_recursion = 0,0
  59.  
  60.  
  61. #Time each function 5 times, take average:
  62. #------------------------------------------
  63.  
  64. for i in range(5):
  65.     total_loop += timer_func(multiLoop, aList)
  66.     total_recursion += timer_func(multiply, aList)
  67. total_loop /= 5
  68. total_recursion /= 5
  69.  
  70.  
  71. #Console feedback
  72. #------------------------------------------
  73.  
  74. print("Loops took {}, recursion took {}.".format(total_loop, total_recursion))
  75. print("Loops were {} times faster".format(total_recursion, total_loop))
Advertisement
RAW Paste Data Copied
Advertisement