DEV Community

Angela
Angela

Posted on

Python custom sum to speed up summation of range objects

If you have an object of type range in python, you can use the arithmetic progression formula to perform the sum of its elements.

Sn = (n/2) [2a + (n-1)d]

Where,
n: total number of elements
a: first element
d: common difference

Create a custom sum in python to speed up summation of objects of type range.

def custom_sum(obj):
    if isinstance(obj, range):
        n = len(obj)
        a = obj.start
        d = obj.step
        return (n * (2 * a + (n - 1) * d)) / 2
    else:
        return sum(obj)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)