提交 fb86c460 authored 作者: Virgile Andreani's avatar Virgile Andreani 提交者: Ricardo Vieira

Improve printing.char_from_number

上级 5cbd3dfa
...@@ -63,23 +63,35 @@ _logger = logging.getLogger("pytensor.printing") ...@@ -63,23 +63,35 @@ _logger = logging.getLogger("pytensor.printing")
VALID_ASSOC = {"left", "right", "either"} VALID_ASSOC = {"left", "right", "either"}
def char_from_number(number): def char_from_number(number: int) -> str:
"""Convert numbers to strings by rendering it in base 26 using capital letters as digits.""" """Convert a number to a string.
base = 26 It renders it in base 26 using capital letters as digits.
For example: 3·26² + 2·26¹ + 0·26⁰ → "DCA"
rval = "" Parameters
----------
number : int
The number to be converted.
if number == 0: Returns
rval = "A" -------
str
The converted string.
"""
base = 26
remainders = []
while number != 0: while number != 0:
remainder = number % base number, remainder = number // base, number % base
new_char = chr(ord("A") + remainder) remainders.append(remainder)
rval = new_char + rval
number //= base
return rval if not remainders:
remainders = [0]
return "".join(chr(ord("A") + r) for r in remainders[::-1])
@singledispatch @singledispatch
......
...@@ -17,6 +17,7 @@ from pytensor.printing import ( ...@@ -17,6 +17,7 @@ from pytensor.printing import (
PatternPrinter, PatternPrinter,
PPrinter, PPrinter,
Print, Print,
char_from_number,
debugprint, debugprint,
default_printer, default_printer,
get_node_by_id, get_node_by_id,
...@@ -30,6 +31,22 @@ from pytensor.tensor.type import dmatrix, dvector, matrix ...@@ -30,6 +31,22 @@ from pytensor.tensor.type import dmatrix, dvector, matrix
from tests.graph.utils import MyInnerGraphOp, MyOp, MyVariable from tests.graph.utils import MyInnerGraphOp, MyOp, MyVariable
@pytest.mark.parametrize(
"number,s",
[
(0, "A"),
(1, "B"),
(25, "Z"),
(26, "BA"),
(27, "BB"),
(3 * 26**2 + 2 * 26 + 0, "DCA"),
(42421337, "DOVPLX"),
],
)
def test_char_from_number(number: int, s: str):
assert char_from_number(number) == s
@pytest.mark.skipif(not pydot_imported, reason="pydot not available") @pytest.mark.skipif(not pydot_imported, reason="pydot not available")
def test_pydotprint_cond_highlight(): def test_pydotprint_cond_highlight():
# This is a REALLY PARTIAL TEST. # This is a REALLY PARTIAL TEST.
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论