• R/O
  • SSH

Commit

Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#objective-cqt誰得cocoawindowspythonphprubygameguibathyscaphec翻訳omegat計画中(planning stage)frameworktwittertestdombtronvb.netdirectxarduinopreviewerゲームエンジン

A small kernel of code for playing with Galois fields of arbitrary characteristic


Commit MetaInfo

Révision54f6125563fe5afee1c2a9ce87ec10c7c972baa1 (tree)
l'heure2021-03-29 07:42:16
AuteurEric Hopper <hopper@omni...>
CommiterEric Hopper

Message de Log

Add Python 3.9 type annotations to numtheory_utils.

Change Summary

Modification

diff -r 4dae57893caf -r 54f6125563fe numtheory_utils.py
--- a/numtheory_utils.py Sun Mar 28 15:41:47 2021 -0700
+++ b/numtheory_utils.py Sun Mar 28 15:42:16 2021 -0700
@@ -1,4 +1,11 @@
1-def extended_gcd(x, y):
1+from collections.abc import Collection
2+from typing import Any, Callable, TypeVar
3+
4+__all__ = [
5+ 'extended_gcd', 'print_group_table', 'mult_inverse', 'print_mult_inverses'
6+]
7+
8+def extended_gcd(x: int, y: int):
29 """Return a tuple 't' with three elements such that:
310 t[0) * x + t[1] * y == t[2]
411
@@ -50,8 +57,11 @@
5057 # (1 * 23 - 1 * 16) - 3 * (3 * 16 - 2 * 23) = 7 * 23 - 10 * 16 = 1
5158 # 13 * 16 - 9 * 23 = 1
5259
53-
54-def print_group_table(elements, op):
60+T = TypeVar('T')
61+def print_group_table(
62+ elements: Collection[T],
63+ op: Callable[[T, T], T]
64+):
5565 width = max(len(str(x)) for x in elements)
5666 print(f'{" ":{width}} |', end='')
5767 for a in elements:
@@ -65,7 +75,16 @@
6575 print()
6676
6777
68-def print_mult_inverses(a, b):
78+def mult_inverse(a: int, b: int):
79+ """If possible, return a number n such that a * n mod b == 1, otherwise
80+ raise an exception."""
81+ am, bm, g = extended_gcd(a, b)
82+ if g == 0:
83+ raise ValueError(f"{a} and {b} are not relatively prime.")
84+ return am if am > 0 else b + am
85+
86+
87+def print_mult_inverses(a: int, b: int):
6988 """Prints out the multiplicative inverse of a (mod b) and the multiplicative
7089 inverse of b (mod a).
7190 """