0

I made this program to familiarize myself with recursion and for all intents and purposes it is working.

def alpha_covert(to_print):
    if to_print is 0:
        return 'Z'
    else:
        return chr(int(to_print) + 64)

def order(to_print):
    if to_print <= 26:
        return alpha_covert(to_print)
    else:
        return (str(order(to_print % 26))) + (str(order(to_print / 26)))

Some example outputs:

>>print(order(1))
>>print(order(100))
>>print(order(443))
>>print(order(9001))
>>print(order(9999999999999999))

A
VC
AQ
EHM
O@JIHYHMTURB

For the last output why is there a @? I assumed there was no issue as int isn't declared until I use alpha_covert which by then should only be less than or equal to 26.

Is this some kind of float rounding error?


Some additional samples while I'm trying to self-solve this. I don't know what this means:

>>print(order(9999999999999997))
>>print(order(9999999999999998))
>>print(order(9999999999999999))

M@JIHYHMTURB
N@JIHYHMTURB
O@JIHYHMTURB
Andy Wong
  • 229
  • 1
  • 2
  • 11

1 Answers1

2

The problem here is that:

if to_print is 0:

happens before you've converted to_print to an integer. Also, you should really be using equality (==) not identity (is); small integers are interned in CPython, but this is an implementation detail you shouldn't rely on.

The simplest fix is:

if to_print == '0':  # compare to string, and by equality

but a better way is to convert the number first, and use the fact that zero numerical values evaluate false-y:

def alpha_convert(to_print):  # note typo in function name
    """A docstring would be nice, too!"""
    to_print = int(to_print)
    return chr(to_print + 64) if to_print else 'Z'
jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
  • I tried your suggestion, I'm still getting the same outputs. – Andy Wong Jul 29 '15 at 17:01
  • @AndyWong sure? `alpha_covert('0')` worked fine for me after the edit, and `order(9999999999999999) == 'OZJIHYHMTURB'`. I've added another, more idiomatic alternative. – jonrsharpe Jul 29 '15 at 17:03
  • Thank you this worked. Can you refer me to documentation for this syntax? I'm not entirely familiar with what this does. `return chr(to_print + 64) if to_print else 'Z'` – Andy Wong Jul 29 '15 at 17:06