Oct-14-2017, 02:18 PM
well, I don't think it is correct to compare these two. itertools.accumulate will iterate over len(a_lit) number of sums, and you a calculating just the last one.
it's correct to compare with sum
however, you can use formula, e.g. sum of arithmetic progression or geometric progression only in some cases, depending of the sequence
e.g. if the list has random numbers, formula will not help
it's correct to compare with sum
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 def by_sum(a_list): print("\nTotal from sum = ", sum(a_list)) 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)) start_3 = time.time() third = by_sum(a_list) print('third took {0:0.10f} seconds'.format(time.time() - start_3))
Output:Total from itertools = 500000500000
first took 0.0474508 seconds
Total from formula = 500000500000
second took 0.0000219345 seconds
Total from sum = 500000500000
third took 0.0085046291 seconds
however, you can use formula, e.g. sum of arithmetic progression or geometric progression only in some cases, depending of the sequence
e.g. if the list has random numbers, formula will not help