Skip to content

Commit fb86c46

Browse files
ArmavicaricardoV94
authored andcommitted
Improve printing.char_from_number
1 parent 5cbd3df commit fb86c46

File tree

2 files changed

+40
-11
lines changed

2 files changed

+40
-11
lines changed

pytensor/printing.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,23 +63,35 @@
6363
VALID_ASSOC = {"left", "right", "either"}
6464

6565

66-
def char_from_number(number):
67-
"""Convert numbers to strings by rendering it in base 26 using capital letters as digits."""
66+
def char_from_number(number: int) -> str:
67+
"""Convert a number to a string.
6868
69-
base = 26
69+
It renders it in base 26 using capital letters as digits.
70+
For example: 3·26² + 2·26¹ + 0·26⁰ → "DCA"
7071
71-
rval = ""
72+
Parameters
73+
----------
74+
number : int
75+
The number to be converted.
7276
73-
if number == 0:
74-
rval = "A"
77+
Returns
78+
-------
79+
str
80+
The converted string.
81+
"""
82+
83+
base = 26
84+
85+
remainders = []
7586

7687
while number != 0:
77-
remainder = number % base
78-
new_char = chr(ord("A") + remainder)
79-
rval = new_char + rval
80-
number //= base
88+
number, remainder = number // base, number % base
89+
remainders.append(remainder)
8190

82-
return rval
91+
if not remainders:
92+
remainders = [0]
93+
94+
return "".join(chr(ord("A") + r) for r in remainders[::-1])
8395

8496

8597
@singledispatch

tests/test_printing.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
PatternPrinter,
1818
PPrinter,
1919
Print,
20+
char_from_number,
2021
debugprint,
2122
default_printer,
2223
get_node_by_id,
@@ -30,6 +31,22 @@
3031
from tests.graph.utils import MyInnerGraphOp, MyOp, MyVariable
3132

3233

34+
@pytest.mark.parametrize(
35+
"number,s",
36+
[
37+
(0, "A"),
38+
(1, "B"),
39+
(25, "Z"),
40+
(26, "BA"),
41+
(27, "BB"),
42+
(3 * 26**2 + 2 * 26 + 0, "DCA"),
43+
(42421337, "DOVPLX"),
44+
],
45+
)
46+
def test_char_from_number(number: int, s: str):
47+
assert char_from_number(number) == s
48+
49+
3350
@pytest.mark.skipif(not pydot_imported, reason="pydot not available")
3451
def test_pydotprint_cond_highlight():
3552
# This is a REALLY PARTIAL TEST.

0 commit comments

Comments
 (0)