반응형
Description:
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input --> Output)
1 --> 1
2 --> 3 + 5 = 8
Solution:
1. Add up all 'n' numbers.
2. Find the odd number by the added number.
3. It returns after adding 'n' odd numbers from the last.
def row_sum_odd_numbers(n):
sum_n = sum(range(n+1))
odd, arr = 1, []
for _ in range(1, sum_n+1):
arr.append(odd)
odd += 2
return sum(arr[sum_n-n:])
Best Practices:
def row_sum_odd_numbers(n):
return n ** 3
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Odd or Even? (0) | 2022.04.30 |
---|---|
Sort array by string length (0) | 2022.04.29 |
Mumbling (0) | 2022.04.27 |
Two to One (0) | 2022.04.26 |
Apparently-Modifying Strings (0) | 2022.04.26 |