DEV Community

Angela
Angela

Posted on

3 1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more