Reputation: 2179
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
Upvotes: 15
Views: 15879
Reputation: 327
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...
Upvotes: 1
Reputation: 839254
Find the logarithm and truncate it:
def power_two(n):
return int(math.log(n, 2))
Upvotes: 28
Reputation: 414915
You could use bit_length():
def power_two(n):
return n.bit_length() - 1
By definition for n != 0
: 2**(n.bit_length()-1) <= abs(n) < 2**n.bit_length()
Upvotes: 23
Reputation: 5565
Two ways, first works only in Python 2.7 and maybe 3+:
import random
for number in (random.randint(0,1<<32) for _ in range(16)):
print "%20i,%4i, %4i" % (number, number.bit_length()-1, len(bin(number))-3)
Upvotes: 6