[SOLVED] Conversion of denary number to binary number problem (Python)

Issue

Im stuck on a problem where I have to write a function that converts a denary number into a binary number using the repeated division by two algorithm. Steps Include:

  • The number to be converted is divided by two.
  • The remainder from the division is the next binary digit. Digits are added to the front of the sequence.
  • The result is truncated so that the input to the next division by two is always an integer.
  • The algorithm continues until the result is 0.

Please click the link below to see what the output should be like:
https://i.stack.imgur.com/pifUO.png

def dentobi(user):
  denary = user
  divide = user / 2
  remainder = user % 2
  binary = remainder
  
  if user != 0:
    print("Denary:", denary)
    print("Divide by 2:", divide)
    print("Remainder:", remainder)
    print("Binary:", binary)
  
user = int(input("Please enter a number: "))
dentobi(user)

This is what I have done so far but Im not getting anywhere.

Can someone explain how I would do this?

Solution

The Answer provided by @user2390182 is functionally correct except that it returns an empty string when num is zero. However, I have noted on several occasions that divmod() is rather slow. Here are three slightly different techniques and their performance statistics.

import time

# This is the OP's original code edited to allow for num == 0
def binaryx(num):
    b = ""
    while num:
        num, digit = divmod(num, 2)
        b = f"{digit}{b}"
    return b or '0'

# This is my preferred solution
def binaryo(n):
    r = []
    while n > 0:
        r.append('1' if n & 1 else '0')
        n >>= 1
    return ''.join(reversed(r)) or '0'

# This uses techniques suggested by my namesake
def binaryy(n):
    r = ''
    while n > 0:
        r = str(n & 1) + r
        n >>= 1
    return r or '0'

M = 250_000

for func in [binaryx, binaryo, binaryy]:
    s = time.perf_counter()
    for _ in range(M):
        func(987654321)
    e = time.perf_counter()
    print(f'{func.__name__} -> {e-s:.4f}s')

Output:

binaryx -> 1.3817s
binaryo -> 0.9861s
binaryy -> 1.6052s

Answered By – Arthur King

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.