def floor_log(num, base):    if num < 0:       raise ValueError(Non-negative number only.)    exponent = 0    while num > 1:        num >>= 1        exponent += 1    return base << (exponent - 1)print floor_log(3, 2) #2 print floor_log(4, 2) #4print floor_log(5, 2) #4print 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.
Largest power of two less than N in Python
python;algorithm;python 2.7;integer
I am surprised you don't just use the math functions you have included in your function name... but, then I see that you have a real bug in your code too.You declare a base parameter, but it only works if the base is the value 2. Bit Shifting is always a base-2 operation.If you really want to find the largest base exponent less than num, then you should use the math library:import mathdef floor_log(num, base):    if num < 0:       raise ValueError(Non-negative number only.)    if num == 0:       return 0    return base ** int(math.log(num, base))Essentially, your code only works for base 2.If you want to do a looping solution similar to your bitshifting, then try:def floor_log(num, base):    if num < 0:       raise ValueError(Non-negative number only.)    if num == 0:       return 0    exponent = 0    while num >= base:        num /= base        exponent += 1    return base ** exponentYou should probably add tests in there for special cases, like the input equals to base, or 1, or 0.See the code running here in ideone