Skip to content

Instantly share code, notes, and snippets.

View JamesTheAwesomeDude's full-sized avatar

James E. A. JamesTheAwesomeDude

View GitHub Profile
@JamesTheAwesomeDude
JamesTheAwesomeDude / Multiset.py
Last active June 14, 2023 23:56
SortedList-based Multiset
"""Multiset implementation.
"""
__all__ = ["Multiset"]
from sortedcontainers import SortedList # https://pypi.org/project/sortedcontainers/
from collections import Counter, deque
@JamesTheAwesomeDude
JamesTheAwesomeDude / joint_groupby.py
Last active July 7, 2023 13:23
groupby multiple iterables in parallel
def joint_groupby(*iterables, key=None, ordered=True):
"""Like itertools.groupby, but iterates through a collection of iterables.
If the value type (or the return type of key) is not comparable, you MUST pass ordered=False.
Example: [(x, tuple(sum(1 for _ in group) for group in groups)) for x, groups in joint_groupby(...)]"""
if key is None:
key = lambda x: x
iterables = [iter(it) for it in iterables]
stop = object()
buffer = [next(it, stop) for it in iterables]
@JamesTheAwesomeDude
JamesTheAwesomeDude / xgcd.py
Last active June 6, 2023 18:55
extended euclidean algorithm python
def xgcd(a, b):
"https://anh.cs.luc.edu/331/notes/xgcd.pdf"
x, x_ = 1, 0
y, y_ = 0, 1
while b:
q, b, a = *divmod(a, b), b
x, x_ = x_, x - q*x_
y, y_ = y_, y - q*y_
#assert a0*x + b0*y == math.gcd(a0, b0)
return x, y
@JamesTheAwesomeDude
JamesTheAwesomeDude / ez_generator_interface.py
Last active June 6, 2023 18:50
Wrapper function to ease generator-driven query-response pattern
def _ez_generator_interface(g):
"""Handy wrapper for generator-driven program flows.
Example usage:
def g(questions=[("What's 3 + 3?", 6), ("What's 9 + 10?", 19)]):
"Example generator function that yields queries expecting a reply"
for question, correct_answer in questions:
answer = yield question # <- KEY LINE
if int(answer) != correct_answer:
@JamesTheAwesomeDude
JamesTheAwesomeDude / postparse.py
Last active March 16, 2024 22:40
parse POST data without cgi module, for Python 3.11+
import email.message, email.parser, email.policy
import urllib.parse
import re
from collections import namedtuple
try:
from resource import getpagesize
except ImportError:
import mmap
def getpagesize():
return mmap.PAGESIZE
@JamesTheAwesomeDude
JamesTheAwesomeDude / last_qualified.py
Last active June 9, 2023 18:40
Get the last element of a sequence matching some predicate
def last_qualified(predicate, iterable, /, return_if_exhausted=True):
"""
Consumes iterable or sequence `iterable` until finding an item
not satisfying `predicate`, or until exhausted, then returns the last item
which satisfied `predicate`.
Raises ValueError if `iterable` is empty.
Raises ValueError if the first item from `iterable` does not satisfy `predicate`.
@JamesTheAwesomeDude
JamesTheAwesomeDude / normalized_lru.py
Last active March 24, 2023 14:39
Normalize function inputs before LRU cache
import functools
from .. import NORMALIZE_FUNC, EXPENSIVE_API_CALL
@(lambda t: lambda f: functools.wraps(f)(lambda x: f(t(x))))(NORMALIZE_FUNC)
@functools.lru_cache
def f(x):
return EXPENSIVE_API_CALL(x)
@JamesTheAwesomeDude
JamesTheAwesomeDude / createxmldoc.js
Last active February 21, 2023 15:30
Firefox/Chrome DOM stdlib: create XML document from scratch, including declaration
// example: createXMLDocumentWithDeclaration('http://www.topografix.com/GPX/1/1', 'gpx', null, 'version="1.0" standalone="yes"')
function createXMLDocumentWithDeclaration(namespaceURI, qualifiedNameStr, documentType=null, declarationData='version="1.0"') {
const document = new Document().implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
// https://www.w3.org/TR/xml/#NT-XMLDecl
document.insertBefore(document.createProcessingInstruction("xml", declarationData), document.firstChild);
return document;
}
@JamesTheAwesomeDude
JamesTheAwesomeDude / istartswith.py
Last active January 13, 2023 21:47
Python: iterable startswith()
from operator import eq as _eq
from itertools import starmap as _starmap, chain as _chain, repeat as _repeat
def _istartswith(a, b):
"""
Returns True if every element of b is equal to the zip-corresponding element of a;
returns False otherwise, including in the event that a has fewer elements than b.
"""
return all(_starmap(_eq, zip(_chain(a, _starmap(object, _repeat(()))), b)))
@JamesTheAwesomeDude
JamesTheAwesomeDude / clmul.py
Last active December 26, 2022 20:27
Carry-less product in Python
from operator import xor as _xor
from functools import reduce as _reduce
# James Edington <james.edington@uah.edu>
# h/t https://wunkolo.github.io/post/2020/05/pclmulqdq-tricks/
# h/t https://en.wikipedia.org/wiki/Carry-less_product
def clmul(a: int, b: int) -> int:
partial_products = ( b*(a & 1<<k) for k in range(a.bit_length()) )
return _reduce(_xor, partial_products, 0)