Raymond Hettinger <rhettin...@users.sourceforge.net> added the comment:
Of course, the name should have been bit_length() instead of numbits(). For the code equivalent, I'm aiming for something less process oriented and more focused on what it does. bit_length IS the number of bits in a binary representation without the sign or leading zeroes -- that definition IS a correct mental picture and does not require special cases for zero or for negatives. The purpose of the code equivalent is not efficiency or beauty; it to help communicate was a function does. If you want it to be more beautiful, it can be broken into multiple lines. I don't think you gain ANY explanatory power with code that says: bit_length is the number of right-shifts (or floor divisions by two) of the absolute value of a number until that number becomes zero. Tell that description to a high school student and prepare for a blank stare. FWIW, I think having a mental picture that was too process oriented was behind last night's mistake of thinking the (16).bit_length() was 5 instead of 4. I theorize that error wouldn't have occurred if the mental picture was of len('10000') instead of power-of-two mental model where people (including some of the commenter here) tend to get the edge cases wrong. It would be better to have no code equivalent at all than to present the repeated //2 method as a definition. That is a process, but not a useful mental picture to help explain what bit_length is all about. Think about it, bit_length() is about the length in bits of a binary representation -- any code provided needs to translate directly to that definition. def bit_length(x): '''Length of a binary representation without the sign or leading zeroes: >>> (-37).numbits() 6 ''' s = bin(x) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and sign return len(s) _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue3439> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com