Skip to content

Instantly share code, notes, and snippets.

View james4388's full-sized avatar
🎯
Focusing

Nhu H Trinh james4388

🎯
Focusing
View GitHub Profile
@james4388
james4388 / skiplist.py
Created November 10, 2019 06:35
Skip list data structure, used for sliding window. Implement by Raymond Hettinger
# http://code.activestate.com/recipes/576930-efficient-running-median-using-an-indexable-skipli/
# Updated to run with python
from random import random
from math import log, ceil
class Node(object):
__slots__ = 'value', 'next', 'width'
def __init__(self, value, next, width):
self.value, self.next, self.width = value, next, width
@james4388
james4388 / disjoinset.py
Last active November 8, 2019 21:03
Disjoin set, union find
class DisjointSet(object):
roots = None
ranks = None
count = 0
def __init__(self, size):
# Each node is parent of itself
self.roots = list(range(size))
self.ranks = [0] * size
self.count = size
@james4388
james4388 / tile.py
Last active September 11, 2019 00:42
Random problem
import string
import random
base_case = [
[(0, 1), (1, 1), (1, 0)], # 0, Top Left
[(0, 0), (1, 0), (1, 1)], # 1, Top Right
[(0, 0), (0, 1), (1, 1)], # 2, Bottom Left
[(0, 1), (0, 0), (1, 0)] # 3, Bottom Right
]
@james4388
james4388 / LFUCache.py
Last active August 30, 2019 00:59
Least frequency cache O(1) implementation using nested DoublyLinkedList and dictionary
"""Least frequency cache implementation using nested DoublyLinkedList and dictionary
Use bucket of frequency count B[1] contain all Item(key, value) with frequency 1
DEMO ONLY do not use in prod
Example
B[1] B[5] B[6]
I[1, 1] I[4, 4] I[5, 5]
I[2, 2]
I[3, 3]
@james4388
james4388 / rotate.py
Last active August 24, 2019 18:49
Rotate matrix, inplace
def rotate(mat: List, clockwise: bool=True) -> None:
""" Rotate matrix inplace but look like it still use extra memory. run on C """
if clockwise:
mat[:] = map(list, zip(*mat[::-1]))
else:
mat[:] = map(list, list(zip(*mat))[::-1])
return mat
def rotate(mat: List, clockwise: bool = True) -> None:
@james4388
james4388 / concurrent_utils.py
Created July 20, 2019 00:27
Thread/Process runner helper. (pre async era)
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
def task_runner(opts):
if isinstance(opts, (list, tuple)):
num_opts = len(opts)
args = None
kwargs = None
if num_opts == 2:
fn, args = opts
elif num_opts == 3:
@james4388
james4388 / heap.py
Created June 19, 2019 16:15
Heap implement
import math
from cStringIO import StringIO
class Heap(object):
''' index from parent
0 0
1 2 0*2+1=1 0*2+2=2
3 4 5 6 1*2+1=3 1*2+2=4 2*2+1=5 2*2+1=6
7 8 9 10 11 12 13 14 3*2+1=7
@james4388
james4388 / mongo_statistic_agg.js
Created June 15, 2019 01:17
Aggregate deep nested mongo
db.getCollection('article').aggregate([
{$match: {$or: [
{"view.sections.parts.embed.provider_name": {$in: ['Commerce Product', 'Image With Hotspots', 'Commerce Product Group']}},
{"view.sections.steps.parts.embed.provider_name": {$in: ['Commerce Product', 'Image With Hotspots', 'Commerce Product Group']}}
]}},
{$project: {_id: 1}
])
db.getCollection('article').aggregate([
{$match: {$or: [
@james4388
james4388 / CSVexport.js
Created June 7, 2019 22:28
Generate CSV with javascript
function csvBlob(rows, export_bom) {
const BOM = '\ufeff'; // Utf-8 Bytes order mark
return new Blob([(export_bom ? BOM : '') + rows.map(function(row) {
return row.map(function(col) {
return ['"', col.replace(/"/gi, '""'), '"'].join('');
}).join(',')
}).join('\n')], {type: 'text/csv;charset=utf-8;'});
}
const blob = csvBlob(temp1);
@james4388
james4388 / total_memory_usage.py
Created June 2, 2019 06:38
Approx. calculate memory ussage by object in Python
from __future__ import print_function
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
try:
from reprlib import repr
except ImportError:
pass
def total_size(o, handlers={}, verbose=False):