Sum of numbers from 0 to N in Python

The challenge

We want to generate a function that computes the series starting from 0 and ending until the given number.

Example:

Input: > 6

Output: 0+1+2+3+4+5+6 = 21

Input: > -15

Output: -15<0

Input: > 0

Output: 0=0

The solution in Python code

Option 1:

def show_sequence(n): if n == 0: return "0=0" elif n < 0: return str(n) + "<0" else: counter = sum(range(n+1)) return '+'.join(map(str, range(n+1))) + " = " + str(counter)
Code language: Python (python)

Option 2:

def show_sequence(n): s = '0' for i in range(1, n+1): s+='+'+str(i) return s+' = '+str(n*(n+1)//2) if n>0 else '0=0' if n==0 else str(n)+'<0'
Code language: Python (python)

Option 3:

def show_sequence(n): if n < 0: return str(n) + "<0" if n == 0: return str(n) + "=0" summ = sum(range(n+1)) numstr = "+".join(map(str, range(n+1))) return numstr + " = " + str(summ)
Code language: Python (python)

Test cases to validate our solution

import test from solution import show_sequence @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): tests = ( (6, "0+1+2+3+4+5+6 = 21"), (7, "0+1+2+3+4+5+6+7 = 28"), (0, "0=0"), (-1, "-1<0"), (-10, "-10<0"), ) for inp, exp in tests: test.assert_equals(show_sequence(inp), exp) @test.describe("Random Tests") def _(): from random import randint def reference(n): if n < 0: return "%s<0" % n if n == 0: return "0=0" return "%s = %s" % ("+".join(map(str, range(0, n+1))), n * (n + 1) // 2) for _ in range(100): test_case = randint(-100, 101) @test.it(f"testing for show_sequence({test_case})") def test_case(): test.assert_equals(show_sequence(test_case),reference(test_case))
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments