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:
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)
Option 2:
def cube_odd(arr):
if len(set(map(type,arr))) < 2:
return sum(n**3 for n in arr if n%2)
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
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)