Oct-14-2017, 01:57 PM
I haven't really used itertools so I thought I would try the 'accumulate' attribute against the equivalent math formula. Is it possible that the formula is truly that fast (faster than time itself ?) Or is there a better way to time this.
import itertools import time a_list = [] for member in range(1, 1000001): a_list.append(member) list_length = len(a_list) def accum(a_list): acc = itertools.accumulate(a_list) for n in acc: total = n print("Total from itertools = ", total) return def by_formula(list_length): same_result = list_length * (list_length + 1) / 2 print("\nTotal from formula = ", int(same_result)) return start_1 = time.time() first = accum(a_list) print('first took {0:0.7f} seconds'.format(time.time() - start_1)) start_2 = time.time() second = by_formula(list_length) print('second took {0:0.10f} seconds'.format(time.time() - start_2))
Output:Total from itertools = 500000500000
first took 0.0312371 seconds
Total from formula = 500000500000
second took 0.0000000000 seconds
Process finished with exit code 0