Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Comparing the for loop to iteration for calculating the product of the numbers in an array
- June 2017, JM
- """
- from time import time
- from sys import setrecursionlimit
- #Function Declarations:
- #------------------------------------------
- def multiLoop(*args):
- '''
- returns the product of the elements in
- args via iteration.
- Expects all args to by numbers
- '''
- total = 1
- for i in range(len(args)):
- total *= aList[i]
- return total
- def multiply(*args):
- '''
- returns the product of the elements in
- args via recursion.
- Expects all args to be numbers
- '''
- def recursive_product(nums):
- '''
- Recursively updates the product of the
- array nums, returns if length 1
- '''
- if len(nums) > 1:
- return nums[0] * recursive_product(nums[1:])
- else:
- return nums[0]
- return recursive_product(args)
- def timer_func(func, arg):
- '''
- wrapper function for timing
- other functions.
- Expects a function and a single arguments
- '''
- start = time()
- func(*arg)
- stop = time()
- return stop - start
- #Increase recursion limit, initiate vars:
- #------------------------------------------
- setrecursionlimit(10003)
- aList = list(range(1,9999))
- total_loop,total_recursion = 0,0
- #Time each function 5 times, take average:
- #------------------------------------------
- for i in range(5):
- total_loop += timer_func(multiLoop, aList)
- total_recursion += timer_func(multiply, aList)
- total_loop /= 5
- total_recursion /= 5
- #Console feedback
- #------------------------------------------
- print("Loops took {}, recursion took {}.".format(total_loop, total_recursion))
- print("Loops were {} times faster".format(total_recursion, total_loop))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement