[Tutor] bin to dec conversion puzzlement

Ben Finney ben+python at benfinney.id.au
Mon Apr 20 22:47:17 CEST 2015


Jim Mooney <cybervigilante at gmail.com> writes:

> I can't seem to get my head around this 'simple' book example of
> binary-to-decimal conversion, which goes from left to right:
>
> B = '11011101'
> I = 0
> while B:
>     I = I * 2 + int(B[0])
>     B = B[1:]
>
> print(I)
> >>> 221

That is, IMO, a needlessly confusing way to write that code.

Whoever wrote it is clearly pleased with how clever it is; but
cleverness is almost always a property of *bad* code because it's
difficult to understand at a glance. That's the case here.

One significant problem with the code as written is that it uses a
‘while’ loop and mutates the list, where there's no point; it should
just iterate over items *from* the list without changing it.

Another significant problem is that it uses moronically-short,
completely unexpressive names. This is Python not FORTRAN.

Try this::

    binary_text = '11011101'
    result = 0

    for binary_digit in binary_text:
        # Accumulate powers of 2 for each digit.
        result = result * 2 + int(binary_digit)

    print(result)

> Both methods work but I just can't see how the first one does. Am I
> missing something obvious here?

No, you were missing something needlessly obscured by the badly-written
code. Which book is this? I will be sure never to recommend it.

Hope that helps.

-- 
 \         “Science is a way of trying not to fool yourself. The first |
  `\     principle is that you must not fool yourself, and you are the |
_o__)               easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney



More information about the Tutor mailing list