The goal of this part of the lab is to motivate a right-to-left conversion of decimal numbers into binary form. Thus, you will end up writing a function numToBinary(anInteger) that works as follows:>>> numToBinary(5) '101'
The code I have is:
def isOdd (x): if x%2==1: return('True') if x%2==0: return('False') def numToBinary(x): if n==0: return '' elif isOdd(x): return numToBinary(x//2)+'1' else: return numToBinary(x//2)+'0'
But this returns the string from left to right. Can anyone help me find a way to go from the left to right representation to a right to left representation?
Is this Python?
I don’t see any “left-to-right” problem in your code. However, the function
isOdd that you provided returns Strings (
'True'). It should return Booleans (i.e. remove the single-quotes).
def isOdd (x): if x%2==1: return(True) # <<< THIS if x%2==0: return(False) # <<< AND THIS
Also, you’re using a variable named
numToBinary, which is not defined anywhere (it should be
def numToBinary(x): if x==0: # <<<< THIS! return '' elif isOdd(x): return numToBinary(x//2)+'1' else: return numToBinary(x//2)+'0'
This code should work fine.
If you just want to convert a number to binary, you can use Python’s internal
bin function. Try:
bin(5)[2:] for example.