0

Just started learning DS&A on my own recently and in the Recursion part of the book, it lists the code below as a basic example of Recursion being used to convert an integer into a string:

def to_str(n,base):
convert_string = "0123456789ABCDEF"
if n < base:
    return convert_string[n]
else:
    return to_str(n/base,base) + convert_string[n%base]

When I call the function and print using print(to_str(1453,10)), I get the error: TypeError: string indices must be integers.

What am I doing wrong?

2 Answers 2

1

In Python 3, the / operator always returns a float object, even if the two numbers you're dividing are both integers. If you want integer division, use the // operator instead:

return to_str(n // base, base) + convert_string[n % base]
Sign up to request clarification or add additional context in comments.

Comments

0

You are getting this error because the value for n/base in the second return statement is a float. Just explicitly convert it to integer.

def to_str(n, base):
    if n < base:
        return convert_string[n]
    else:
        return to_str(int(n/base), base) + convert_string[n%base]

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.