I am trying to write a recursive code that can convert a number to any base system. for example, the integer 10 into binary would convert to 1010
So far I have this but
I recommend you structure your code in a more precise way. You can split the vaguely-specified task you mention along different sub-tasks, e.g.:
0
or 1
);a
and b
) returns a
"sequence of digits" to represent a
in
base b
, where a "digit" is an integer
between 0
included and b
excluded;Of these tasks, only the second one can be seen as suitable to a "recursive" implementation if one insists (though an iterative implementation is in fact much more natural!) -- given that this is homework, I guess you'll have to do it recursively because that's part of the assigned task, ah well!-). But, for reference, one obvious way to iterate would be:
def digitsequence(a, b):
results = []
while True:
results.append(a % b)
if a < b: break
a //= b
return reversed(results)
assuming one wants the digit sequence in the "big endian" order we're used to from the way positional decimal notation entered Western culture (it was the more naturally-computed little-endian order in the Arabic original... but Arab being written right-to-left, the literal transcription of that order in European languages, written left-to-right, became big-endian!-).
Anyway, you can take simple, linear recursion as a way to "reverse" things implicitly (you could say such recursion "hides" a last-in, first-out stack, which is clearly a way to reverse a sequence;-), which I guess is where the recursion spec in the homework assignment may be coming from;-).