[英]Made a recursive program to convert the column position into an Excel column (1 = A, 27 = AA), getting @'s in my output
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
. 我以为没有问题,因为直到我使用
alpha_covert
声明int
,那时alpha_covert
只能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
The problem here is that: 这里的问题是:
if to_print is 0:
happens before you've converted to_print
to an integer . 在将
to_print
转换为整数之前发生。 Also, you should really be using equality ( ==
) not identity ( is
); 另外,您实际上应该使用等于(
==
)而不是identity( is
); small integers are interned in CPython, but this is an implementation detail you shouldn't rely on. 小整数会在CPython中进行实习,但这是您不应该依赖的实现细节。
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 : 但是更好的方法是先转换数字,并使用零数值评估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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.