daco2020 2022. 4. 28. 22:40

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