Skip to content

Instantly share code, notes, and snippets.

View Yossarian0916's full-sized avatar
:octocat:
RTFSC

Yossarian42 Yossarian0916

:octocat:
RTFSC
View GitHub Profile
@Yossarian0916
Yossarian0916 / dijkstra.py
Created December 14, 2019 13:43
implement dijkstra algorithm using my own implementation of priority queue
from collections import defaultdict
class PriorityQueue:
"""
each heap element is in form (key value, object handle), while heap
operations works based on comparing key value and object handle points to
the corresponding application object.
"""
@Yossarian0916
Yossarian0916 / merge_sort.py
Created June 7, 2019 13:41
merge sort python implementation
def merge_sort(array):
if len(array) == 1:
return array
else:
mid = len(array) // 2
left = merge_sort(array[:mid])
right = merge_sort(array[mid:])
return merge(left, right)
@Yossarian0916
Yossarian0916 / quick_sort.py
Last active June 1, 2019 04:12
quick sort algorithm python implementation, and test case with randomly generated array
import random
def partition(array, l, r):
pivot = array[l] # choose the 1st element as the pivot
i = l+1
for j in range(l+1, r):
if array[j] < pivot:
array[j], array[i] = array[i], array[j]
i += 1
@Yossarian0916
Yossarian0916 / count_inversions.py
Last active May 26, 2019 04:50
count the inversions of a given array, for example, if the a is greater than b, but the index of a is smaller than b, this makes one inversion
"""
compute the number of inversions of the given array
running time is O(nlogn)
using divide and conquer
"""
def count_split_inv(array, left, right):
count = 0
i, j = 0, 0
length = len(left) + len(right)
@Yossarian0916
Yossarian0916 / zodiac_gf.py
Created April 26, 2019 11:31
how many girls should one date before he can be in a relationship with all 12 zodiac sign
"""
how many girls should one date before he can be in a relationship with
all 12 zodiac signs
"""
import random
def simulation():
count = 0
gf = set()
@Yossarian0916
Yossarian0916 / karatsuba_mul.py
Last active April 28, 2019 20:53
Karatsuba multiplication in python3
from math import floor, ceil
"""
implement Karatsuba algorithm O(n ** log3)
"""
# karatsuba multiplication
def karatsuba(a, b, base=10):
"""
divide each number into two halves, the high bits H and the low bits L