[Tutor] Using built-in divmod( ) function
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Oct 3 19:38:26 EDT 2020
On 03/10/2020 20:18, Manprit Singh wrote:
> Consider a problem , where i have to write a program which converts an
> integer to its binary equivalent.
integers are stored in binary on the computer, there is no need
to convert it to binary. It is already there.
You may be thinking of its binary representation, which is a
string that appears when we print it. That can be achieved
using the built in bin() function.
> 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)
This is a variant of the classic "find the binary representation
of a decimal number" algorithm we all learnt in high school.
Except this one produces a decimal number that looks
like a binary number, which is plain wrong! Now we have two
different integers both stored in binary and printing differently.
> .... Now m y question is why we are not using a
> divmod operator in this case ?
Most languages do not have a single divmod() function.
So basic algorithm classes won;t use it. But if you are
doing a divmod operation, as here, it makes sense to use
it if available. But it makes even more sense to use a
function that does what was asked in the first place,
namely bin()
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list