0

all, I have this code that, for the life of me, I can't figure out how to solve this TypeError.

def dtobr(n):
    if n == 0:
        return 0
    else:
        return (n % 2) + 10 * dtobr(int(n / 2))

I need it to return as a string (project requirement for class). The math is correct, but when I change the last line to

return str((n % 2) + 10 * dtobr(int(n / 2)))

I get

"TypeError: unsupported operand type(s) for +: 'int' and 'str'".

I have tried setting "return (n % 2) + 10 * dtobr(int(n / 2))" to x, setting y to int(x) and returning y, and I've have no clue (and Google isn't offering any solutions that I can try to apply to my problem) what else I can do. Any ideas would be helpful!!

2
  • "I need it to return as a string" why? Commented Oct 28, 2018 at 5:13
  • The type error is because you're calling dtobr on the result of dtobr, and it multiplies with an int. Commented Oct 28, 2018 at 5:14

3 Answers 3

1

Doing str() on the return means that all the recursive calls will also return a str, so you need to either convert those returns back to a int, e.g.:

def dtobr(n):
    if n == 0:
        return '0'
    else:
        return str((n % 2) + 10 * int(dtobr(n // 2)))

In []:
dtobr(10)

Out[]:
'1010'

Or just use a helper function to do the conversion:

def dtobr(n):
    return str(dtobr_(n))

def dtobr_(n):
    if n == 0:
        return 0
    else:
        return (n % 2) + 10 * dtobr_(n // 2)

In []:
dtobr(10)

Out[]:
'1010'

But I don't see why just calling str(dtobr(10)) wouldn't be equally as good.

Note: // is integer division so you don't need to int(n/2), n//2 will do.

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like:

def dtobr(n):
   n = int(n)
   if n == 0:
      return 0
   else:
      return str((n % 2) + 10 * int(dtobr(int(n / 2))))

Comments

0

Both solutions offered so far involve conversions to str and int and back again. I don't think that's necessary and we can solve this without int() and multiplication:

def dtobr(n):
    if n == 0:
        return '0'

    return dtobr(n // 2).lstrip('0') + str(n % 2)

The trick is to do the recursion ahead of the current digit, instead of the other way around. This avoids the conversion back to int and the multiplication by 10.

EXAMPLE

>>> dtobr(12)
'1100'
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.