Home > OS >  Square root of a number with python bisect?
Square root of a number with python bisect?

Time:07-16

We can get square root of complete square with bisect as follows:

import bisect

def squareRootUsingBisect(num):
    return bisect.bisect_left(list(range(0,num)), num, lo=0, hi=num, key=lambda v: v*v)
print(squareRootUsingBisect(169))

appropriately prints square root of 169:

13

The problem is that it also prints a number for non-complete square:

print(squareRootUsingBisect(170))

prints

14

which is misleading. Can I determine if bisect has indeed found the value or not, and print -1 or null if it has not?

CodePudding user response:

bisect_left only gives you the nearest root. If you want to check whether num actually is a real square, you have to check afterwards (bisect doesn't come with an option to do that)

import bisect

def squareRootUsingBisect(num):
    n = bisect.bisect_left(list(range(0,num)), num, lo=0, hi=num, key=lambda v: v*v)
    return n if n*n == num else -1
print(squareRootUsingBisect(170)) # gives -1
print(squareRootUsingBisect(169)) # gives 13

CodePudding user response:

Could you just add an if check in the function

if bisect_calc != num ** 0.5:
    return -1
  • Related