Skip to content

Instantly share code, notes, and snippets.

@carlosgmartin
carlosgmartin / nfgs.py
Created June 12, 2020 21:42
Solving batches of two-player zero-sum normal-form games
import numpy as np
import gurobipy
import cvxopt
from multiprocessing import Pool
from timeit import default_timer as timer
gurobipy.setParam('OutputFlag', 0)
def max_min_gurobi(game):
model = gurobipy.Model()
v = model.addMVar(1)
@carlosgmartin
carlosgmartin / mobius.py
Created July 13, 2019 00:08
Computes the Möbius transform of arithmetic sequences
import numpy as np
import sympy.ntheory
import time
# https://mathoverflow.net/a/227408/74578
def mobius_transform(sequence):
sequence = sequence.copy()
for i in range(1, len(sequence)//2+1):
sequence[i+i-1::i] -= sequence[i-1]
return sequence
@carlosgmartin
carlosgmartin / stackermann.py
Created June 20, 2019 07:00
Stack-based implementation of the Ackermann function
# https://www.sciencedirect.com/science/article/pii/0304397588900461
def stackermann(i, n):
stack = []
stack.append(i)
stack.append(n)
while len(stack) > 1:
n = stack.pop()
i = stack.pop()
if i == 0:
@carlosgmartin
carlosgmartin / vigenere.py
Created June 20, 2019 06:36
Python implementation of the Vigenère cipher
from itertools import cycle, count
import string
alphabet = string.ascii_lowercase + string.ascii_uppercase + ' ' + string.digits + string.punctuation
encode = dict(zip(alphabet, count())).get
decode = dict(zip(count(), alphabet)).get
add = lambda a, b: decode((encode(b) + encode(a)) % len(alphabet))
sub = lambda a, b: decode((encode(b) - encode(a)) % len(alphabet))
@carlosgmartin
carlosgmartin / hausdorff.py
Last active June 20, 2019 06:37
Demo of Hausdorff distance between a point and a fuzzy set
import torch
import torchvision
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.backend_bases import MouseEvent
import torch
def onclick(event):
x = torch.tensor([event.ydata, event.xdata]).float()
d = (y - x).float().norm(dim=-1)
@carlosgmartin
carlosgmartin / qlearning_parallel.py
Last active June 20, 2019 06:39
Q learning with multiple simultaneous agents
import numpy as np
from time import sleep
from itertools import count
from pdb import set_trace
import matplotlib.pyplot as plt
def softmax(x):
y = np.exp(x - x.max(-1, keepdims=True))
return y / y.sum(-1, keepdims=True)
@carlosgmartin
carlosgmartin / numpy-neuralnet
Created September 16, 2018 19:19
Pure-numpy neural network on CIFAR10 dataset
import numpy
import torch
import torchvision
import matplotlib.pyplot as plt
def relu(x):
return numpy.maximum(0, x)
def relu_derivative(x):
return (x > 0).astype(float)