Skip to content

Instantly share code, notes, and snippets.

@EdisonChendi
EdisonChendi / 1320_minimum_distance_to_type_a_word_using_two_fingers.py
Created March 11, 2020 14:51
leetcode algorithms 1320 - minimum_distance_to_type_a_word_using_two_fingers
import unittest
import string
import collections
from pprint import pprint
# def print(*args, **kwargs):
# pass
def make_table(letters, width):
table = {}
import unittest
import re
def permutations(ops, len):
if len == 1:
return [[op] for op in ops]
l = []
for i, op in enumerate(ops):
for s in permutations(ops, len-1):
l.append([op,]+s)
@EdisonChendi
EdisonChendi / programmation_efficace_2_1.py
Created July 29, 2018 13:07
find all anagrams in a sentence
#coding:UTF-8
from collections import defaultdict
def find_anagrams(setence):
words = set(setence.split())
dd = defaultdict(list)
for w in words: # O(nklgk)
dd["".join(sorted(w))].append(w)
return {k:v for k, v in dd.items() if len(v) > 1} # O(n)
@EdisonChendi
EdisonChendi / graph_bfs.py
Last active June 10, 2018 09:29
graph + breadth first search
#coding:UTF-8
class Graph:
def __init__(self):
# use dict to store the graph
# the number of keys in self.ves is the number of vertices in the graph
# the total number of values(list) is the sum of degree of each vertex
self.ves = {}
@EdisonChendi
EdisonChendi / radix_sort.py
Last active May 27, 2018 08:51
radix sort in python
#coding:UTF-8
from random import randint
from functools import partial
from counting_sort import counting_sort
'''
for simplicity: use base 10
b - base
k - range of values of keys of the input
@EdisonChendi
EdisonChendi / counting_sort.py
Last active May 27, 2018 08:46
counting sort in Python
#coding:UTF-8
from random import randint
from math import inf
'''
running time: O(n+k)
'''
def counting_sort(arr, n, k, key=lambda x: x):
@EdisonChendi
EdisonChendi / binary_search_tree.py
Last active May 6, 2018 08:48
binary search tree
#coding:UTF-8
'''
notes on R5
What is a data structure?
Algorithms for you to query update store information
BST
query:
@EdisonChendi
EdisonChendi / heap_sort.py
Last active April 24, 2018 15:50
heap sort
#coding:UTF-8
def heapify(arr, i):
# O(lgn)
left_idx = 2*i+1
if left_idx >= len(arr):
return
right_idx = left_idx + 1
if right_idx >= len(arr):
left = arr[left_idx]
@EdisonChendi
EdisonChendi / merget_sort.py
Created April 14, 2018 13:06
merge sort + merge n sorted list with variable length
#coding:UTF-8
import math
def merge_sort(l):
if len(l) <= 1:
return l
mid_idx = (len(l)-0)//2
@EdisonChendi
EdisonChendi / insertion_sort.py
Created April 14, 2018 13:05
insertion sort
#codint:UTF-8
def insertion_sort(l):
if len(l) <= 1:
return l
for i in range(1, len(l)):
key = l[i]
for j in reversed(range(0, i)):
c = l[j]
if c > key: