Browse Source

first commit

pull/1/head
wes 7 years ago
commit
7fd1b6a704
  1. 30
      bfs.py
  2. 48
      bst.py
  3. 16
      fib.hs
  4. 23
      intersection.py
  5. 19
      palindrome.py
  6. 10
      pascal.hs
  7. 14
      pascal.py
  8. 37
      phone.py
  9. 62
      regions.py
  10. 39
      reverse_list.py

30
bfs.py

@ -0,0 +1,30 @@
#! /usr/bin/env python3
# breadth first traversal of a binary tree
from collections import deque
class Branch:
def __init__(self, v, left, right):
self.v = v
self.left = left
self.right = right
def bfs(tree, process):
nodes = deque([tree])
current_node = None
while nodes:
current_nodes = list(nodes)
for node in current_nodes:
current_node = node
process(current_node.v)
nodes.popleft()
if not current_node.left is None:
nodes.appendleft(current_node.left)
if not node.right is None:
nodes.appendleft(current_node.right)
test = Branch(1, Branch(2, Branch(3, None, None), Branch(4, None, None)),
Branch(5, None, None))
bfs(test, print)

48
bst.py

@ -0,0 +1,48 @@
#! /usr/bin/env python2
from random import randint
from pprint import PrettyPrinter
# Construct a binary search tree
# Also create a function to search it
pp = PrettyPrinter(indent=4)
class Branch:
def __init__(self, left, value, right):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return "(%s) %s (%s)" % (repr(self.left), self.value, repr(self.right))
def split(xs):
l = len(xs) / 2
return (xs[0:l], xs[l], xs[l+1:])
def bst(xs):
if not xs:
return None
left, middle, right = split(xs)
return Branch(bst(left), middle, bst(right))
def makeBST(xs):
return bst(sorted(xs))
def findBST(tree, x):
if tree is None:
return None
print tree.value
if tree.value == x:
return tree
if x < tree.value:
return findBST(tree.left, x)
else:
return findBST(tree.right, x)
test = [randint(1,50) for _ in range(20)]
print test
print "finding %s" % test[4]
print findBST(makeBST(test), test[4])

16
fib.hs

@ -0,0 +1,16 @@
#! /usr/bin/env runghc
-- get the nth fibonnaci number in linear time
import qualified Data.List as L
fibs = L.unfoldr
(\(prev, cur) -> Just (prev, (cur, prev+cur)))
(0, 1)
getNthFib n = fibs !! n
main = do
print $ getNthFib 1
print $ getNthFib 7
print $ getNthFib 100

23
intersection.py

@ -0,0 +1,23 @@
#! /usr/bin/env python2
# find the intersection of two lists including duplicate values
from collections import defaultdict
def frequencies(xs):
freqs = defaultdict(int)
for x in xs:
freqs[x] += 1
return freqs
def intersection(fs1, fs2):
xs = []
for k, v in fs1.iteritems():
n = min(v, fs2[k])
xs.extend([k for _ in xrange(n)])
return xs
fs1 = frequencies([1,4,2,6,10,4,4])
fs2 = frequencies([7,4,9,10,20,4,10])
print intersection(fs1, fs2)

19
palindrome.py

@ -0,0 +1,19 @@
#! /usr/bin/env python2
# check if a word is palindromic without reversing it
def isPalindrome(word):
end = len(word)
start = 0
foo = True
while start < end+1:
left = word[start]
right = word[end-1]
if left != right:
foo = False
break
start += 1
end -= 1
return foo
print isPalindrome("wwaabbaawwz")

10
pascal.hs

@ -0,0 +1,10 @@
module Main where
-- find the rows of pascal's triangle
choose n 0 = 1
choose n k = (choose n (k-1)) * (n-k) `div` k
pascal n = [choose n i | i <- [0..n-1]]
main = mapM_ print $ map pascal [1..100]

14
pascal.py

@ -0,0 +1,14 @@
#! /usr/bin/env python2
# find the rows of pascal's triangle
def choose(n, k):
if k == 0:
return 1
return choose(n, k-1) * (n-k) / k
def pascal(n):
return [choose(n, i) for i in xrange(0, n)]
for i in xrange(1, 11):
print pascal(i)

37
phone.py

@ -0,0 +1,37 @@
#! /usr/bin/env python2
# find all possible permutations of a sequence of phone pad digits (other than 1 and 0)
from itertools import chain
mappings = {
2 : "ABC",
3 : "DEF",
4 : "GHI",
5 : "JKL",
6 : "MNO",
7 : "PQRS",
8 : "TUV",
9 : "WXYZ"
}
def generate(letter, letters):
return [letter + c for c in letters]
def genWords(one, two):
return list(chain.from_iterable([generate(c, two) for c in one]))
def genAll(lettersets):
if len(lettersets) == 1:
return lettersets
first = lettersets[0]
rest = lettersets[1:]
return [genWords(first, ls) for ls in genAll(rest)]
def numToWords(num):
lettersets = [mappings[int(n)] for n in num]
return genAll(lettersets)[0]
for num in numToWords("353346"):
print num

62
regions.py

@ -0,0 +1,62 @@
#! /usr/bin/env python2
# counts the number of regions in a matrix
# vertically and horizontally connected
# e.g.
# [1, 0, 1, 1]
# [0, 1, 0, 0]
# [1, 1, 0, 1]
# has 4 regions
class Patch(object):
def __init__(self, visited, value):
self.visited = visited
self.value = value
def __repr__(self):
return "visited = %s, value = %s" % (self.visited, self.value)
def initialize(region):
for row in region:
yield [Patch(visited=False, value=field) for field in row]
testregion = list(initialize([
[True, False, True, True],
[False, True, False, False],
[True, True, False, True]
]))
columns = len(testregion[0])
rows = len(testregion)
def exploreField(region, x, y):
# check if we've reached the edge of the matrix
if (x < 0 or y < 0):
return True
try:
if region[y][x].visited or not region[y][x].value:
return True
except IndexError:
return True
region[y][x].visited = True
exploreField(region, y+1, x)
exploreField(region, y-1, x)
exploreField(region, y, x+1)
exploreField(region, y, x-1)
count = 0
for y, row in enumerate(testregion):
for x, patch in enumerate(row):
# if a patch is both unvisited and true
# this means exploreField will eliminate it
# so it counts as one region
if not patch.visited and patch.value:
count += 1
exploreField(testregion, x, y)
print count

39
reverse_list.py

@ -0,0 +1,39 @@
#! /usr/bin/env python3
# reverse a linked list
class LinkedList:
def __init__(self, head, tail):
self.head = head
self.tail = tail
def __repr__(self):
return "%s%s" % (self.head, "" if self.tail is None else ",%s" % repr(self.tail))
def cons(x, xs):
return LinkedList(x, xs)
xs = cons(1, cons(2, cons(3, cons(4, cons(5, None)))))
def push(x, xs):
prev = xs.head
xs.head = x
xs.tail = cons(prev, xs.tail)
def reverseLinkedList(xs):
current = xs.head
rest = xs.tail
revd = None
while True:
if revd is None:
revd = cons(current, None)
else:
push(current, revd)
if rest is None:
break
current = rest.head
rest = rest.tail
return revd
print(reverseLinkedList(xs))
Loading…
Cancel
Save