我可能在一种特殊情况下,将空字符串评估为true会节省几行代码。(我理解空字符串评估为false。如下)
'' and print ("empty string is true")
'0' and print ("non-empty string is true")
> non-empty string is true
原因如下:
这样就可以了。但是请检查输出。
def baseN(num,b):
return (num == 0) and "0" or
(baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])
> baseN(32,16)
> 020
更改最后一个结果(在递归末尾)以打印出空字符串,给我错误。
def baseN(num,b):
return (num == 0) and "" or
( baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])
> baseN(32,16)
> File "<stdin>", line 2, in baseN
> RuntimeError: maximum recursion depth exceeded in comparison
这显然是行不通的,因为(num==0) and "" (false)
它将始终评估为False->导致未终止的递归调用。
有没有一种方法可以仅使用逻辑运算/表达式(不使用if / else语句)来修复它?
以下将起作用。但是它不会只使用逻辑运算符。
def baseN(num,b):
if (num==0):
return ""
else:
return (baseN(num // b, b)
+ "0123456789abcdefghijklmnopqrstuvwxyz"[num % b])
baseN(32,16)
Python具有三元运算符:
def baseN(num,b):
return baseN(num // b, b) + "0123456789abcdefghijklmnopqrstuvwxyz"[num % b] if num else ""
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句