0

Im going through the book Problem Solving with Algorithms and Data Structures for Python. Im in chapter 4 and am using the examples. This example is straight from the book, yet when I run it its nothing but errors. Is this a mistake in the book or am i missing something here?

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]

print(to_str(1453, 16))

When I run this I get these errors:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in to_str
  File "<stdin>", line 6, in to_str
  File "<stdin>", line 4, in to_str
TypeError: string indices must be integers

Is the book wrong or am I missing something? If Its my fault, what could I be missing Ive reread this chapter in full twice now. Im not missing anything in the text.

ruohola
  • 21,987
  • 6
  • 62
  • 97
Anon_guy
  • 155
  • 10
  • 3
    It is probably for Python 2. In Python 3 division (`/`) between numbers always return float values (see [Division in Python 2.7. and 3.3](https://stackoverflow.com/q/21316968/1782792)). Try replacing `n / base` with `n // base` which will perform an integer division instead and also works fine in Python 2.7. – jdehesa Mar 06 '19 at 17:11
  • 1
    Yeah that worked! I was thrown off since the examples all show print with the parentheses so I assumed this was in python 3. The book is old(2014). I guess Ill look for a new one. This stuff is complicated enough, Being given the wrong or outdated info wont help me at all. – Anon_guy Mar 06 '19 at 17:25

1 Answers1

0

Your book is written for Python 2; there a / b always returns an integer.

In Python 3 (which you're using); a / b results in a float value (aka decimal), if you want integer result in Python 3 you can use a // b.

ruohola
  • 21,987
  • 6
  • 62
  • 97