Created
January 11, 2024 23:04
-
-
Save mfm24/1558821871e4ce3a525e7456bd3cb7af to your computer and use it in GitHub Desktop.
Ring arithmetic in Python. Condensed version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import islice, cycle, tee | |
def a(n, dict_class=dict): | |
a, b = tee(cycle(dict_class() for __ in range(n))) | |
for d in islice(a, n): | |
d.update(dict(enumerate(islice(b, n)))) | |
ret = next(b) | |
return ret | |
class IdDict(dict): | |
def __getitem__(self, __key): | |
return dict.__getitem__(self, id(__key)) | |
def __setitem__(self, __key, __value): | |
dict.__setitem__(self, id(__key), __value) | |
class g(IdDict): | |
def __init__(self, base_dict, init_val, next_val_f): | |
# Start with init_val, and call next_val_f for each item | |
curr = {k: init_val for k in base_dict.keys()} | |
for d in base_dict.values(): | |
self[d] = curr | |
# add k to each v | |
curr = {k: next_val_f(k, v) for k, v in curr.items()} | |
d = a(100) | |
m = g(d, d[0], lambda k, v: v[k]) | |
p = g(d, d[1], lambda k, v: m[v][k]) | |
# 2**3 * 3 + 6 = 30? | |
assert m[p[d[3]][2]][3][6] is d[30] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment