반응형
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 :)
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Easy SQL: LowerCase (0) | 2022.05.13 |
---|---|
SQL Basics: Simple WHERE and ORDER BY (0) | 2022.05.12 |
Round up to the next multiple of 5 (0) | 2022.05.10 |
Find the capitals (0) | 2022.05.09 |
Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages (0) | 2022.05.08 |