patternpythonModerate
"Largest power of two less than N" in Python
Viewed 0 times
thanpowerlargesttwolesspython
Problem
def floor_log(num, base):
if num 1:
num >>= 1
exponent += 1
return base << (exponent - 1)
print floor_log(3, 2) #2
print floor_log(4, 2) #4
print floor_log(5, 2) #4
print floor_log(6, 2) #4I frequently miss the edge cases like
while num or while num > 1. What is good strategy to avoiding these mistakes? apart from this the function seems fine to me. Comments are most welcome.Solution
If what you really want is the "largest power of 2", you should make that more explicit:
And does the largest power of two less than
If you want error check, you can add the value error if you want (note only positive
Don't write loops when you don't need to.
def largest_power_of_two(n):And does the largest power of two less than
n mean in terms of bits? It's just dropping all of the bits except for the left-most one. Since we can get the bit length of a number directly, we can just do that:def largest_power_of_two(n):
return 1 << (n.bit_length() - 1)If you want error check, you can add the value error if you want (note only positive
ns are valid, you initially allowed for 0... but what is the largest power of 2 less than or equal to 0?):def largest_power_of_two(n):
if n > 0:
return 1 << (n.bit_length() - 1)
else:
raise ValueError("only meaningful for positive values")Don't write loops when you don't need to.
Code Snippets
def largest_power_of_two(n):def largest_power_of_two(n):
return 1 << (n.bit_length() - 1)def largest_power_of_two(n):
if n > 0:
return 1 << (n.bit_length() - 1)
else:
raise ValueError("only meaningful for positive values")Context
StackExchange Code Review Q#105911, answer score: 11
Revisions (0)
No revisions yet.