[Tutor] Using built-in divmod( ) function

Cameron Simpson cs at cskk.id.au
Sat Oct 3 17:11:22 EDT 2020


On 04Oct2020 00:48, Manprit Singh <manpritsinghece at gmail.com> wrote:
>Consider a problem , where i have to write a program which converts an
>integer to its binary equivalent. I have seen so many books following this
>approach:
>
>x = int(input("Enter a number"))
>b, i = 0, 0
>while x != 0:
>    r = x % 2
>    b = b + (r * (10**i))
>    x = x // 2
>    i = i + 1
>print(b)
>
>Upon a user input =10, the value b (or the desired output ) becomes 1010
>which is the right answer . Now m y question is why we are not using a
>divmod operator in this case ? I would prefer writing the above program in
>the following way, using divmod( ) :
>
>x = int(input("Enter a number"))
>b, i = 0, 0
>while x != 0:
>    x, r = divmod(x, 2)
>    b = b + (r * (10**i))
>    i = i + 1
>print(b)
>
>What way should i prefer ? need your suggestions .

I would prefer your way - it is shorter and probably faster. And once 
the reader has looked up divmod(), it is clearer because the divmod() 
encapsulates the relationship of the formerly separate % and // lines.

The former method has the advantage that it spells our each operation, 
which is useful from a teaching perspective.

All that said, they are both bad. Why? Because they produce an integer 
which is not the original value, it just _happens_ to be printed out 
_like_ the binary representation of the original value when rendered in 
base 10.

If I were decomposing a value into its binary form I would want to get 
an array of bits, not a (much larger) value which happened to "print 
right". If I want something _printed_ in base 2 I've usualy reach for 
the bin() function, which produces a _string_.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list