The main problem is you miss return
:
def integerCubeRootHelper(n, left, right):
cube = lambda x: x * x * x # anonymous function to cube a number
assert (n >= 1)
assert (left < right)
assert (left >= 0)
assert (right < n)
assert (cube(left) < n), f'{left}, {right}'
assert (cube(right) > n), f'{left}, {right}'
mid = (left + right) // 2
if (left == mid):
return left
elif (cube(mid) > n):
return integerCubeRootHelper(n, left, mid)
else:
return integerCubeRootHelper(n, mid, right)
def integerCubeRoot(n):
if (n == 1):
return 1
if (n == 2):
return 1
return integerCubeRootHelper(n, 0, n - 1)
print(integerCubeRoot(3))
And some more advice about your code that can help you to increase code correctness and readability:
- Your functions' name should be lowercase. Link
- You have to remove redundant parentheses.
- Always use a
def
statement instead of an assignment statement that binds a lambda expression directly to a name. Link
Full PEP 8 style guide
Updated version:
def integer_cube_root_helper(n, left, right):
def cube(x):
return x * x * x
assert n >= 1
assert left < right
assert left >= 0
assert right < n
assert cube(left) < n, f'{left}, {right}'
assert cube(right) > n, f'{left}, {right}'
mid = (left + right) // 2
if left == mid:
return left
elif cube(mid) > n:
return integer_cube_root_helper(n, left, mid)
else:
return integer_cube_root_helper(n, mid, right)
def integer_cube_root(n):
if n == 1:
return 1
if n == 2:
return 1
return integer_cube_root_helper(n, 0, n - 1)
print(integer_cube_root(3))