Thursday, February 29, 2024
HomeSoftware EngineeringSum of Odd Cubed Numbers in Python

# Sum of Odd Cubed Numbers in Python

## The problem#

Discover the sum of the odd numbers inside an array, after cubing the preliminary integers. The operate ought to return `None` if any of the values aren’t numbers.

Be aware: Booleans shouldn’t be thought of as numbers.

## The answer in Python code#

Possibility 1:

``````def cube_odd(arr):
if any(kind(x) is just not int for x in arr):
return None
return sum(x ** 3 for x in arr if x % 2 != 0)
``````

Possibility 2:

``````def cube_odd(arr):
if len(set(map(kind,arr))) < 2:
return sum(n**3 for n in arr if npercent2)
``````

Possibility 3:

``````def cube_odd(arr):
s = 0
for n in arr:
if kind(n) != int: break
elif npercent2: s += n**3
else:
return s
``````

## Check instances to validate our resolution#

``````import take a look at
from resolution import cube_odd

@take a look at.describe("Mounted Assessments")
def fixed_tests():
@take a look at.it('Primary Check Instances')
def basic_test_cases():
take a look at.assert_equals(cube_odd([1, 2, 3, 4]), 28)
take a look at.assert_equals(cube_odd([-3,-2,2,3]), 0)
take a look at.assert_equals(cube_odd(["a",12,9,"z",42]), None)
take a look at.assert_equals(cube_odd([True,False,2,4,1]), None)

@take a look at.describe("Random checks")
def _():

from random import randint, random

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

for _ in vary(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 vary(randint(5,10))],key=lambda a: random())
anticipated = sol(arr)
@take a look at.it(f"Testing for cube_odd({arr})")
def _():
take a look at.assert_equals(cube_odd(arr[:]),anticipated)
``````
RELATED ARTICLES