# Solve The Triangle of Odd Numbers using Python ## The challenge

Given the triangle of consecutive odd numbers:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```             1
3     5
7     9    11
13    15    17    19
21    23    25    27    29
...``````

Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:

``````row_sum_odd_numbers(1); # 1
row_sum_odd_numbers(2); # 3 + 5 = 8```Code language: Python (python)```

## Test cases

``````Test.assert_equals(row_sum_odd_numbers(1), 1)
Test.assert_equals(row_sum_odd_numbers(2), 8)
Test.assert_equals(row_sum_odd_numbers(13), 2197)
Test.assert_equals(row_sum_odd_numbers(19), 6859)
Test.assert_equals(row_sum_odd_numbers(41), 68921)
```Code language: Python (python)```

## The solution in code

While there are many ways to achieve this, the absolute most simple is to realise that the solution is just a `n^3`.

``````def row_sum_odd_numbers(n):
return n*n*n
```Code language: Python (python)```

Another way is to do it the more Pythonic way:

``````def row_sum_odd_numbers(n):
return n ** 3
```Code language: Python (python)```
Tags:
Subscribe
Notify of 1 Comment
Inline Feedbacks 