# Sum of Odd Cubed Numbers in Python

## The challenge

Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return `None` if any of the values aren’t numbers.

Note: Booleans should not be considered as numbers.

## The solution in Python code

Option 1:

```.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%}```def cube_odd(arr):
if any(type(x) is not int for x in arr):
return None
return sum(x ** 3 for x in arr if x % 2 != 0)
```Code language: Python (python)```

Option 2:

``````def cube_odd(arr):
if len(set(map(type,arr))) < 2:
return sum(n**3 for n in arr if n%2)
```Code language: Python (python)```

Option 3:

``````def cube_odd(arr):
s = 0
for n in arr:
if type(n) != int: break
elif n%2: s += n**3
else:
return s
```Code language: Python (python)```

## Test cases to validate our solution

``````import test
from solution import cube_odd

@test.describe("Fixed Tests")
def fixed_tests():
@test.it('Basic Test Cases')
def basic_test_cases():
test.assert_equals(cube_odd([1, 2, 3, 4]), 28)
test.assert_equals(cube_odd([-3,-2,2,3]), 0)
test.assert_equals(cube_odd(["a",12,9,"z",42]), None)
test.assert_equals(cube_odd([True,False,2,4,1]), None)

@test.describe("Random tests")
def _():

from random import randint, random

sol=lambda arr: None if any(type(e)!=int for e in arr) else sum(e*e*e for e in arr if e%2)
base=["a","b","c",True,False]

for _ in range(40):
arr=[randint(-10,10) for q in range(randint(5,10))]
arr=arr if randint(0,1) else sorted(arr+[base[randint(0,len(base)-1)] for q in range(randint(5,10))],key=lambda a: random())
expected = sol(arr)
@test.it(f"Testing for cube_odd({arr})")
def _():
test.assert_equals(cube_odd(arr[:]),expected)
```Code language: Python (python)```
Tags:
Subscribe
Notify of