Sum of numbers from 0 to N in Python

[ad_1]

The problem

We need to generate a operate that computes the sequence ranging from 0 and ending till the given quantity.

Instance:

Enter: > 6

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

Enter: > -15

Output: -15<0

Enter: > 0

Output: 0=0

The answer in Python code

Choice 1:

def show_sequence(n):
    if n == 0:
        return "0=0"
    elif n < 0:
        return str(n) + "<0"
    else:
        counter = sum(vary(n+1))
        return '+'.be part of(map(str, vary(n+1))) + " = " + str(counter)

Choice 2:

def show_sequence(n):
    s = '0'
    for i in vary(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'

Choice 3:

def show_sequence(n):

    if n < 0:
        return str(n) + "<0"
    if n == 0:
        return str(n) + "=0"
        
    summ = sum(vary(n+1))
    numstr = "+".be part of(map(str, vary(n+1)))
    
    return numstr + " = " + str(summ)

Check circumstances to validate our answer

import check
from answer import show_sequence

@check.describe("Mounted Exams")
def fixed_tests():
    @check.it('Fundamental Check Instances')
    def basic_test_cases():
        exams = (
            (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 exams:
            check.assert_equals(show_sequence(inp), exp)
            
@check.describe("Random Exams")
def _():
    
    from random import randint    
    
    def reference(n):
        if n < 0:
            return "%s<0" % n
        if n == 0:
            return "0=0"            
        return "%s = %s" % ("+".be part of(map(str, vary(0, n+1))), n * (n + 1) // 2)    
    
    for _ in vary(100):
        test_case = randint(-100, 101)
        @check.it(f"testing for show_sequence({test_case})")
        def test_case():
            check.assert_equals(show_sequence(test_case),reference(test_case))

[ad_2]

Leave a Reply