find largest power of two less than X number?

Viewed 14342

I m doing this

def power_two(n, base = -1):
    result = 2 ** base
    if result < n:
        base += 1
        power_two(n, base)
    else:
        if result == n:
            print base
        else:
            print base - 1

what is the pythonic way to find largest power of two less than X number?

EDIT example: power_two(100) return only the power

5 Answers

utilising the power of .format!

def maxPowOf2(n):
     return len("{0:b}".format(n))-1

This answer is similar and maybe slower than @jfs though...
translates the number into a binary string and finds the length.
Won't work properly on negative numbers though...

Related