Skip to content

Instantly share code, notes, and snippets.

@righthandabacus
righthandabacus / atexit.py
Created January 2, 2019 04:04
Exit signal - work around the lack of UNIX signal in Windows
import atexit
import time
import logging
import signal
import os
def sighandler(sigcode, x):
print("Signal Exit!!", flush=True)
print([sigcode, x], flush=True)
exitcall()
@righthandabacus
righthandabacus / permutation-heap.py
Created February 9, 2019 01:24
Using Heap Algorithm to generate all permutation
def heapalgo(items, n):
"""heap algorithm to generate all permutations in-place
Args:
items: list of items
n: initially the list of items, only permute on the first n-items
Generates:
a permutation of first n items of the list, in-place shuffle performed
"""
assert items, "cannot go with empty list"
@righthandabacus
righthandabacus / minrange.py
Created February 16, 2019 20:19
Min range to cover all lists
#!/usr/bin/env python
"""
Given $k$ sorted lists, each of size $n$, find a range $(p,q)$ such that:
1. q-p is minimized
2. for any list, there is an element $r$, such that $p <= r <= q$
Example:
[4, 10, 15, 24]
[0, 9, 12, 20]
@righthandabacus
righthandabacus / selrank.py
Created February 23, 2019 21:22
Selection rank algorithm demo
"""Selecton rank algorithm
"""
import random
def selrank(array, start, stop, k):
"""return the k-th largest element (0-th = max) in sliced list
`array[start:stop]` using the selection rank algorithm
This move the larger elements of array to lower indices such that at the end
@righthandabacus
righthandabacus / hypchoid.py
Created March 7, 2019 02:45
Hyperchoid and hypochoid animated GIF creator
import argparse
from math import sin, cos, radians, gcd
from typing import Tuple, List
import numpy as np
from PIL import Image, ImageDraw
RADIANS = np.pi / 180
DIMENSION = (500, 500) # coordinate origin at centre
@righthandabacus
righthandabacus / pyann.py
Created March 21, 2019 23:26
Artificial neural network with only numpy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provide class of a generic ANN for classification (using binary cross entropy)
"""
import numpy as np
# define activation functions g(Z), and their first derivative, using numpy
# hold all activation function pairs in a global dict
@righthandabacus
righthandabacus / netcat.py
Last active March 26, 2019 20:46
netcat in python
import socket
import socketserver
import threading
def sender(hostname, port, content):
"""Connect to a TCP port and send content, then wait for reply
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((hostname, port))
sock.sendall(content)
@righthandabacus
righthandabacus / wpct.py
Created January 13, 2020 03:49
weighted percentile function
def weighted_percentile(a, q, weights=None, interpolation='step'):
"""
Compute the qth percentile of the data a, optionally weight can be provided.
Returns the qth percentile(s) of the array elements.
Methodology
-----------
If weights are not provided, we set all `a` of equal weight of 1. Then we
normalize the weight by equal factor so that their sum is 1. Then, in sorted
ascending order of `a`, we plot the values as a curve from 0 to 1 and lookup
@righthandabacus
righthandabacus / dictionaries.py
Created September 18, 2020 05:01
Raymond Gettinger, Modern Python Dictionaries: A confluence of a dozen great idea, PyCon 2017
# typed from video: youtu.be/npw4s1QTmPg
# Raymond Gettinger, Modern Python Dictionaries: A confluence of a dozen great idea, PyCon 2017
from __future__ import division, print_function
import array
import collections
import itertools
# Placeholder constants
FREE = -1
@righthandabacus
righthandabacus / slidingwindow.py
Created December 20, 2020 18:28
Sliding window on a 2D array using numpy
def sliding_window(a, win_size):
'''Slding window view of a 2D array a using numpy stride tricks.
For a given input array `a` and the output array `b`, we will have
`b[i] = a[i:i+w]`
Args:
a: numpy array of shape (N,M)
Returns:
numpy array of shape (K,w,M) where K=N-w+1
'''