Is there a faster way to sum up an arithmetic sequence of numbers in Python?

后端 未结 3 865
猫巷女王i
猫巷女王i 2021-01-26 18:15
total = 0
for i in range(0, some upper bound):
    total += i

Sorry if this is basic but I have a lot of these and they\'re taking up more room than is

3条回答
  •  孤街浪徒
    2021-01-26 18:49

    To expand on eumiro. You may want to write a method that encapsulates the Gauss method for clarity. I would suggest something like this (written in Groovy because I don't know Python syntax):

    public int sumUpToBoundary(def upper_bound){
        return (upper_bound) * (upper_bound - 1) / 2;
    }
    
    public int sumBetween(def lower_bound, def upper_bound){
        return sumUpToBoundary(upper_bound) - sumUpToBoundary(lower_bound);
    }
    
    public void someOtherMethod() {
        int total = sumUpToBoundary(some_upper_bound);
        int total2 = sumBetween(some_lower_bound, some_upper_bound);
    }
    

    UPDATE: @mspy noted that my method signatures weren't in the style of Python. I've updated the example to groovy which supports somewhat more Python-like syntax.

提交回复
热议问题