Skip to content

Instantly share code, notes, and snippets.

View ishikawa's full-sized avatar
🏠
Working from home

Takanori Ishikawa ishikawa

🏠
Working from home
View GitHub Profile
def bubble_sort(lst):
"""
>>> bubble_sort([3, 4, 2, 10, 1])
[1, 2, 3, 4, 10]
>>> bubble_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> bubble_sort([])
[]
"""
import logging
steps = 0
def fibonacci_recursive(n):
global steps
steps += 1
if n is 0:
return 0
elif n < 3:
# Knapsack problem
class Item(object):
def __init__(self, value, weight):
self.value, self.weight = value, weight
items = [
None,
Item(4, 2),
# http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK2/NODE46.HTM#SECTION02313000000000000000
def edit_distance(pattern, text):
"""Returns the __edit distance__ value between ``pattern`` and ``text``."""
# n = |P|, m = |T|
n, m = len(pattern), len(text)
matrix = [[0] * (m + 1) for i in xrange(n + 1)]
for i in xrange(n + 1):
matrix[i][0] = i
def longest_increasing_sequence(seq):
L = [0] * len(seq)
P = [0] * len(seq)
for i in xrange(len(seq)):
l, k = 0, -1
for j in xrange(i):
if seq[j] < seq[i] and L[j] > l:
l = L[j]
k = j
def longest_increasing_sequence(seq):
L = [0] * len(seq)
P = [0] * len(seq)
for i in xrange(len(seq)):
l, k = 0, -1
for j in xrange(i):
if seq[j] < seq[i] and L[j] > l:
l = L[j]
k = j
"""
Fast Exponentiation
http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK2/NODE54.HTM#SECTION02361000000000000000
"""
import math
def slow_pow(a, n):
x = 1
for i in xrange(n):
x *= a
(define (fast-pow a n)
(cond ((= n 0) 1)
(else
(let ((x (fast-pow a (quotient n 2))))
(cond ((odd? n) (* a x x))
(else (* x x)))))))
def binary_search(seq, obj):
low, high = 0, len(seq) - 1
while low <= high:
mid = low + ((high - low) / 2)
order = cmp(seq[mid], obj)
if order is 0:
return mid
elif order > 0:
high = mid - 1
else:
def binary_search(seq, obj):
low, high = 0, len(seq) - 1
while low <= high:
mid = low + ((high - low) / 2)
order = cmp(seq[mid], obj)
if order is 0:
return mid
elif order > 0:
high = mid - 1
else: