sandy neo
sandy neo

Reputation: 1

How to return as a string in recursive?

I'm doing decimal to binary using recursion method. However, I was unable to convert it to string using the code below. Any help? <3

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

result = to_binary(nums)
print("Result: " + result)

It's always giving errors:

Updated

Upvotes: 0

Views: 51

Answers (3)

YJR
YJR

Reputation: 1202

In your last line has a mistake.for example consider 3 converts to binary.it must be to_binary(3//2) = to_binary(1) + 3%2=1

def to_binary(d):
  if d == 0:
    return str(0)
  elif(d==1):
     return str(1)
  else:
    return str(to_binary(d // 2)+str(d%2))

Upvotes: 0

Kneidl1202
Kneidl1202

Reputation: 51

Well bro the error is pretty straight forward. Here: return str(d % 2 + 10 * to_binary(int(d // 2))) you call to_binary, which returns a String, but then try to add it with a number d % 2.

Simply change that line to: return str(d % 2 + 10 * int(to_binary(int(d // 2)))). This should solve your error.

Upvotes: 0

queeg
queeg

Reputation: 9394

Likely the formula in the last line is wrong.

Your function should return a string. But then the last line would try to add and multiply a number with a string - what result do you expect?

I suggest this last line:

return to_binary(int(d // 2))) + str(d % 2)

Upvotes: 2

Related Questions