A small kernel of code for playing with Galois fields of arbitrary characteristic
Revision | 0e11b6b32650f9120f975c9fa8e3ca402d4dfee1 (tree) |
---|---|
Time | 2021-07-19 07:56:59 |
Author | Eric Hopper <hopper@omni...> |
Commiter | Eric Hopper |
Make table printout use colors if colorama and blessings is available.
@@ -1,5 +1,10 @@ | ||
1 | -from collections.abc import Collection | |
2 | -from typing import Any, Callable, TypeVar | |
1 | +from typing import Any, Callable, TypeVar, Dict, Collection | |
2 | +try: | |
3 | + import colorama | |
4 | + import blessings | |
5 | + nocolors = False | |
6 | +except ModuleNotFoundError: | |
7 | + nocolors = True | |
3 | 8 | |
4 | 9 | __all__ = [ |
5 | 10 | 'extended_gcd', 'print_group_table', 'mult_inverse', 'print_mult_inverses' |
@@ -62,18 +67,29 @@ | ||
62 | 67 | T = TypeVar('T') |
63 | 68 | def print_group_table( |
64 | 69 | elements: Collection[T], |
65 | - op: Callable[[T, T], T] | |
70 | + op: Callable[[T, T], T], | |
71 | + highlight_map: Dict[T, int] = {} | |
66 | 72 | ): |
73 | + if not nocolors: | |
74 | + colorama.init() | |
75 | + term = blessings.Terminal() | |
67 | 76 | width = max(len(str(x)) for x in elements) |
68 | 77 | print(f'{" ":{width}} |', end='') |
78 | + def element_str(a, width): | |
79 | + s = f'{a:{width}}' | |
80 | + spaces = ' ' * (len(s) - len(str(a))) | |
81 | + if (not nocolors) and (a in highlight_map): | |
82 | + return spaces + term.color(highlight_map[a])(str(a)) | |
83 | + else: | |
84 | + return s | |
69 | 85 | for a in elements: |
70 | - print(f' {a:{width}} |', end='') | |
86 | + print(f' {element_str(a, width)} |', end='') | |
71 | 87 | print() |
72 | 88 | for a in elements: |
73 | - print(f'{a:{width}} |', end='') | |
89 | + print(f'{element_str(a, width)} |', end='') | |
74 | 90 | for b in elements: |
75 | 91 | result = op(a, b) |
76 | - print(f' {result:{width}} |', end='') | |
92 | + print(f' {element_str(result, width)} |', end='') | |
77 | 93 | print() |
78 | 94 | |
79 | 95 |