나는 이렇게 학습한다/Algorithm & SQL

Sum of numbers from 0 to N

daco2020 2022. 5. 11. 21:28
반응형

Description:

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

 

 

 

Solution:

1. If n is 0, "0=0" is returned.
2. If n is negative, "n<0" is returned.
3. If n is a positive number, the addition expression from 0 to n is returned as a string.

def show_sequence(n):
    return (
        n == 0 and "0=0"
    ) or (
        n < 0 and f"{n}<0"
    ) or (
        n > 0 and f"{'+'.join(map(str, range(n+1)))} = {sum(range(n+1))}"
    )

It's fun to solve with logical operators without using if :)

 

 

 

 

반응형