views:

234

answers:

3

iI am trying to write a recursive code that can convert a number to any base system. for example, the interger 10 into binary would convert to 1010

so far i have this but i'm having "None" in between my output. Can anyone help me with my code?

def convert(a,b):
    add = a%b
    if a<=1:
        return a
    else:
        print(base(a//b,b), add)

my idea is that a%b is the number to add to the end of the number and a//b is the recursive part where it uses the answer of the previous binary number so 10 in base 2 is just convert(5,2) and add the 0 at the end since a//b=5 and a%b=0 which = 1010

A: 

The convert function returns None, and print prints it. You should either remove the print call, or accumulate the result as a string and return it.

(I'm assuming that the call to base is actually meant to be a recursive call to convert.)

daf
yes base is actually suppose to be convert. one of the examples given is this:convert(10,2)1 0 1 0when i remove the print and put return, it gives me this "(((1, 0), 1), 0)"
Dan
That's because the comma operator constructs a tuple. See my response which uses string concatenation instead.
danben
i dont think my outcome is suppose to be a string, it should look like this example given: 1 0 1 0
Dan
What do you want it to be, then? It has to be something. If you want spaces in the middle then add spaces.
danben
sorry i'm new to python. how would you add spaces?
Dan
like `str(convert(a//b,b)) + " " + str(add)`, or more Pythonically, `' '.join([str(convert(a//b,b)), str(add)])`
danben
Sorry for poor formatting, but that should be `' '.join`
danben
+1  A: 

You have no return statement in your else block, and you have no recursive call to convert.

I think you want:

if a<=1:
    return str(a)
else:
    return str(convert(a//b,b)) + str(add)

as in

>>> def convert(a,b):
...   add = a%b
...   if a<=1:
...     return str(a)
...   else:
...     return str(convert(a//b,b)) + str(add)
... 
>>> convert(10,2)
'1010'

In general, try to avoid mixing types in recursive functions. It is most often the case that both your base case and your recursive case should return the same type.

danben
You probably ought to index into a table of digits instead of using `str()` if you want to support bases greater than 10.
Mike DeSimone
+1  A: 

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.:

  • determine and normalize the signs of the number and base (do you need to support negative bases, or can you just raise an exception?), also ensuring an immediate exception gets raised in error cases (e.g. a base of 0 or 1);
  • write a function that (give positive and correct values for 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;
  • write a function that given a's sign and sequence-of-digits expansions builds and returns a string representation -- depends on how you want to represent very large "digits" when b is large, say > 36 if you want to use digits, then ASCII letters, for the first 36 digits in the obvious way; maybe you should accept an "alphabet" string to use for the purpose (and the first function above should raise an exception when b's too large for the given alphabet)
  • write a function that uses all the above ones to print the string out

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;-).

Alex Martelli