Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My numerical to binary function is not producing an output

Does anybody have an idea why this function would not generate an output?

import math

def converter (value):
  list1 = []
  list1.reverse()  
  while value >= 0:
   Remainder = value%2
   list1.append(Remainder)
   value /= 2
   math.floor(value) 
  list1.reverse() 
  return list1

converter(17)

The model would not generate an output. After debugging I found the source of the problem value /= 2 changing this to something like value -=2 seem to enable the code to run, however, it is not the output I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Multiple problems with your code. You want to change your condition in the while loop as it runs forever. Also, you need to change the the new assignment of the variable value:

import math

def converter (value):
    list1 = []
    while value > 0:
        remainder = value % 2
        list1.append(remainder)
        value = math.floor(value / 2) 
        
    list1.reverse()
    return list1

converter(17)

Output:

[1, 0, 0, 0, 1]

Edit: I would also remove math.floor() by an integer division:

def converter (value):
    list1 = []
    while value > 0:
        remainder = value % 2
        list1.append(remainder)
        value = value // 2 
        
    list1.reverse()
    return list1

converter(18)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading