[Tutor] bin to dec conversion puzzlement

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Apr 21 13:33:09 CEST 2015


On 20/04/2015 21:47, Ben Finney wrote:
> 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.
>

I agree entirely so a big +1 from me.


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list