Home > katas > Grasshopper - Summation (8kyu) [Python]

Grasshopper - Summation (8kyu) [Python]


Chek kata on Codewars

Description:

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8

Solution 1

Let's start with loop solutions.

def summation(num):
    sum = 0
    for n in range(0, num + 1):
        sum += n
    return sum

Solution 2

Let's solve it with Gauss Formula.

def summation(num):
    return (num * (num + 1) / 2)

Solution 3

Let's solve it with reduce.

# add import => from functools import reduce
def do_sum(acc, cur): return acc + cur
def summation(num): return reduce(do_sum, range(1, num + 1))

Solution 4

Let's solve it with sum.

def summation(num):
    return sum(range(1, num+1))

Solution 5

Let's solve it with recursion.

def summation(num):
    return num + summation(num - 1) if num != 0 else num
© 2021, Andrew Losseff