├── ProblemSolvingAlgorithms.sublime-project ├── ProblemSolvingAlgorithms.sublime-workspace ├── README.md ├── chap01_intro ├── ActiveCode12.py ├── aName.py ├── activeCode10.py ├── activeCode7.py ├── activeCode8.py ├── activeCode9.py ├── andGate.py ├── binaryGate.py ├── complete_circuit.py ├── connector.py ├── half_adder.py ├── listing1.py ├── logic.py~ ├── logicGate.py ├── monkeys.py ├── myFraction.py ├── my_math.py └── unaryGate.py ├── chap02_analysis ├── listing2.py ├── listing3.py ├── quickSort.py ├── randSelect.py ├── selfCheck1.py ├── sumOf.py ├── sumOf.py~ ├── sumOfN2.py └── sumOfN2.py~ ├── chap03_data_structures ├── __pycache__ │ └── stack.cpython-32.pyc ├── baseConverter.py ├── deque.py ├── divideBy2.py ├── hotPotato.py ├── infixToPostfix.py ├── infixToPostfix2.py ├── node.py ├── orderedList.py ├── palChecker.py ├── postfixEval.py ├── queue.py ├── revstring.py ├── simuPrinter.py ├── stack.py ├── unorderedList1.py └── unorderedList2.py ├── chap04_recursion ├── change.py ├── changeDP.py ├── fact.py ├── fact.py~ ├── listSum.py ├── listSum.py~ ├── listSum2.py ├── listSum2.py~ ├── maze.py ├── maze2.txt ├── pal.py ├── pal.py~ ├── reverse.py ├── reverse.py~ ├── spMakeChange.py ├── toStr.py ├── tower.py ├── tower.py~ ├── triangle.py ├── turtle1.py ├── turtle1.py~ ├── turtleTree.py └── turtleTree.py~ ├── chap05_sorting_and_searching ├── binarySearch.py ├── binarySearchRec.py ├── bubbleSort.py ├── hash.py ├── insertionSort.py ├── map.py ├── mergeSort.py ├── orderedSequentialSearch.py ├── quickSort.py ├── selectionSort.py ├── sequentialSearch.py ├── shellSort.py └── shortBubbleSort.py ├── chap06_trees ├── 1-BinaryTree │ ├── binaryTreeExample.py │ ├── binaryTreeLists.py │ └── myTree.py ├── 2-BinaryTreeApplications-ParseTree │ ├── BinaryTree.py │ ├── Stack.py │ └── parseTree.py ├── 3-PriorityQueuesWithBinaryHeaps │ ├── BinHeap.py │ └── testBinHeap.py ├── 4-BinarySearchTree │ ├── #BinarySearchTree.py# │ ├── #TreeNode.py# │ ├── BinarySearchTree.py │ ├── BinarySearchTree.pyc │ ├── BinarySearchTree.py~ │ ├── TreeNode.py │ ├── TreeNode.pyc │ ├── TreeNode.py~ │ ├── __pycache__ │ │ ├── BinarySearchTree.cpython-32.pyc │ │ └── TreeNode.cpython-32.pyc │ └── testBST.py ├── 5-BalancedBinarySearchTrees │ ├── AvlTree.py │ ├── AvlTree.py~ │ ├── BinarySearchTree.py │ ├── BinarySearchTree.pyc │ ├── TreeNode.py │ └── TreeNode.pyc └── __pycache__ │ ├── BinHeap.cpython-32.pyc │ ├── BinaryTree.cpython-32.pyc │ └── Stack.cpython-32.pyc ├── chap07_graphs ├── 01_adjacency_list │ ├── Graph.py │ ├── Graph.pyc │ ├── Graph.py~ │ ├── Vertex.py │ ├── Vertex.pyc │ ├── Vertex.py~ │ ├── __pycache__ │ │ ├── Graph.cpython-32.pyc │ │ └── Vertex.cpython-32.pyc │ ├── testGraph.py │ └── testGraph.py~ ├── 02_breadth_first_search │ ├── Graph.py │ ├── Queue.py │ ├── Vertex.py │ ├── bfs.py │ ├── bfs.py~ │ └── buildGraph.py ├── 03_depth_first_search │ ├── DFSGraph.py │ ├── Graph.py │ ├── Vertex.py │ ├── knightGraph.py │ └── knightTour.py └── 04_shortest_path │ ├── Graph.py │ ├── PriorityQueue.py │ ├── Vertex.py │ ├── dijkstra.py │ └── prim.py └── pythonds ├── Listings.zip ├── Listings ├── listing_1_1.py ├── listing_1_10.py ├── listing_1_11.py ├── listing_1_12.py ├── listing_1_13.py ├── listing_1_14.py ├── listing_1_15.py ├── listing_1_16.py ├── listing_1_2.py ├── listing_1_3.py ├── listing_1_4.py ├── listing_1_5.py ├── listing_1_6.py ├── listing_1_7.py ├── listing_1_8.py ├── listing_1_9.py ├── listing_2_1.py ├── listing_2_10.py ├── listing_2_11.py ├── listing_2_12.py ├── listing_2_2.py ├── listing_2_3.py ├── listing_2_4.py ├── listing_2_5.py ├── listing_2_6.py ├── listing_2_7.py ├── listing_2_8.py ├── listing_2_9.py ├── listing_3_1.py ├── listing_3_10.py ├── listing_3_11.py ├── listing_3_12.py ├── listing_3_13.py ├── listing_3_14.py ├── listing_3_15.py ├── listing_3_16.py ├── listing_3_17.py ├── listing_3_18.py ├── listing_3_19.py ├── listing_3_2.py ├── listing_3_20.py ├── listing_3_21.py ├── listing_3_22.py ├── listing_3_23.py ├── listing_3_24.py ├── listing_3_25.py ├── listing_3_3.py ├── listing_3_4.py ├── listing_3_5.py ├── listing_3_6.py ├── listing_3_7.py ├── listing_3_8.py ├── listing_3_9.py ├── listing_4_1.py ├── listing_4_10.py ├── listing_4_11.py ├── listing_4_12.py ├── listing_4_13.py ├── listing_4_14.py ├── listing_4_15.py ├── listing_4_16.py ├── listing_4_17.py ├── listing_4_2.py ├── listing_4_3.py ├── listing_4_4.py ├── listing_4_5.py ├── listing_4_6.py ├── listing_4_7.py ├── listing_4_8.py ├── listing_4_9.py ├── listing_5_1.py ├── listing_5_10.py ├── listing_5_11.py ├── listing_5_12.py ├── listing_5_13.py ├── listing_5_14.py ├── listing_5_15.py ├── listing_5_2.py ├── listing_5_3.py ├── listing_5_4.py ├── listing_5_5.py ├── listing_5_6.py ├── listing_5_7.py ├── listing_5_8.py ├── listing_5_9.py ├── listing_6_1.py ├── listing_6_10.py ├── listing_6_11.py ├── listing_6_12.py ├── listing_6_13.py ├── listing_6_14.py ├── listing_6_15.py ├── listing_6_16.py ├── listing_6_17.py ├── listing_6_18.py ├── listing_6_19.py ├── listing_6_2.py ├── listing_6_20.py ├── listing_6_21.py ├── listing_6_22.py ├── listing_6_23.py ├── listing_6_24.py ├── listing_6_25.py ├── listing_6_26.py ├── listing_6_27.py ├── listing_6_28.py ├── listing_6_29.py ├── listing_6_3.py ├── listing_6_30.py ├── listing_6_31.py ├── listing_6_32.py ├── listing_6_33.py ├── listing_6_34.py ├── listing_6_35.py ├── listing_6_36.py ├── listing_6_37.py ├── listing_6_38.py ├── listing_6_39.py ├── listing_6_4.py ├── listing_6_5.py ├── listing_6_6.py ├── listing_6_7.py ├── listing_6_8.py ├── listing_6_9.py ├── listing_7_1.py ├── listing_7_10.py ├── listing_7_11.py ├── listing_7_12.py ├── listing_7_2.py ├── listing_7_3.py ├── listing_7_4.py ├── listing_7_5.py ├── listing_7_6.py ├── listing_7_7.py ├── listing_7_8.py ├── listing_7_9.py ├── listing_8_1.py ├── listing_8_10.py ├── listing_8_11.py ├── listing_8_12.py ├── listing_8_13.py ├── listing_8_14.py ├── listing_8_15.py ├── listing_8_16.py ├── listing_8_17.py ├── listing_8_18.py ├── listing_8_19.py ├── listing_8_2.py ├── listing_8_20.py ├── listing_8_21.py ├── listing_8_22.py ├── listing_8_23.py ├── listing_8_24.py ├── listing_8_25.py ├── listing_8_26.py ├── listing_8_27.py ├── listing_8_28.py ├── listing_8_29.py ├── listing_8_3.py ├── listing_8_4.py ├── listing_8_5.py ├── listing_8_6.py ├── listing_8_7.py ├── listing_8_8.py └── listing_8_9.py ├── PythonDSExamplePrograms.zip ├── PythonDSExamplePrograms ├── Chapter1 │ ├── fraction.py │ └── logicgates.py ├── Chapter3 │ ├── baseconverter.py │ ├── hotpotato.py │ ├── infixtopostfix.py │ ├── orderedlist.py │ ├── palindromechecker.py │ ├── parcheckers.py │ ├── printersimulation.py │ ├── stacktest.py │ └── unorderedlist.py ├── Chapter4 │ ├── makingchange.py │ ├── maze.py │ ├── maze2.txt │ ├── recursiveconversion.py │ ├── recursivelistsummation.py │ ├── recursivespiral.py │ ├── recursivetree.py │ ├── recursivetriangle.py │ └── towerofhanoi.py ├── Chapter5 │ ├── binarysearch.py │ ├── binarysearchrecursive.py │ ├── bubblesort.py │ ├── hashing.py │ ├── insertionsort.py │ ├── mergesort.py │ ├── orderedsequentialsearch.py │ ├── quicksort.py │ ├── selectionsort.py │ ├── sequentialsearch.py │ └── shellsort.py ├── Chapter6 │ ├── balancedbst.py │ ├── binarytreelist.py │ ├── binarytreenoderef.py │ ├── binheap.py │ ├── binsearchtree.py │ ├── binsearchtree2.py │ ├── heapexample1.py │ ├── parsetree.py │ └── treeexample.py ├── Chapter7 │ ├── depthfirstsearch.py │ ├── fourletterwords.txt │ ├── graphimpl.py │ ├── rawwords.txt │ ├── wordladder.py │ └── wordproc.py └── pythonds │ ├── __init__.py │ ├── __pycache__ │ └── __init__.cpython-32.pyc │ ├── basic │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-32.pyc │ │ ├── queue.cpython-32.pyc │ │ └── stack.cpython-32.pyc │ ├── deque.py │ ├── queue.py │ └── stack.py │ ├── graphs │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-32.pyc │ │ ├── adjGraph.cpython-32.pyc │ │ └── priorityQueue.cpython-32.pyc │ ├── adjGraph.py │ └── priorityQueue.py │ └── trees │ ├── __init__.py │ ├── __pycache__ │ ├── __init__.cpython-32.pyc │ ├── balance.cpython-32.pyc │ ├── binheap.cpython-32.pyc │ └── bst.cpython-32.pyc │ ├── balance.py │ ├── binaryTree.py │ ├── binheap.py │ ├── bst.py │ └── bst.pyc ├── ReadMe.txt ├── pythonds.zip └── pythonds ├── __init__.py ├── __pycache__ └── __init__.cpython-32.pyc ├── basic ├── __init__.py ├── deque.py ├── queue.py └── stack.py ├── graphs ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-32.pyc │ ├── adjGraph.cpython-32.pyc │ └── priorityQueue.cpython-32.pyc ├── adjGraph.py └── priorityQueue.py └── trees ├── __init__.py ├── __pycache__ ├── __init__.cpython-32.pyc ├── balance.cpython-32.pyc ├── binheap.cpython-32.pyc └── bst.cpython-32.pyc ├── balance.py ├── binaryTree.py ├── binheap.py ├── bst.py └── bst.pyc /ProblemSolvingAlgorithms.sublime-project: -------------------------------------------------------------------------------- 1 | { 2 | "folders": 3 | [ 4 | { 5 | "path": "/Users/HansonE/Dropbox/Documents/Projects/mitOpenCourseWare/6.006-Introduction to Algorithms (Fall 2011)/problemSolving_Algorithms" 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python 2 | ================================================================ 3 | 4 | Examples and work from Problem Solving with Algorithms and Data Structures Using Python 5 | 6 | Thank you. 7 | -------------------------------------------------------------------------------- /chap01_intro/ActiveCode12.py: -------------------------------------------------------------------------------- 1 | 2 | def gcd(m,n): 3 | while m%n != 0: 4 | oldm = m 5 | oldn = n 6 | 7 | m = oldn 8 | n = oldm%oldn 9 | return n 10 | 11 | class Fraction: 12 | def __init__(self,top,bottom): 13 | self.num = top 14 | self.den = bottom 15 | 16 | def __str__(self): 17 | return str(self.num)+"/"+str(self.den) 18 | 19 | def show(self): 20 | print(self.num,"/",self.den) 21 | 22 | def __add__(self,otherfraction): 23 | newnum = self.num*otherfraction.den + \ 24 | self.den*otherfraction.num 25 | newden = self.den * otherfraction.den 26 | common = gcd(newnum,newden) 27 | return Fraction(newnum//common,newden//common) 28 | 29 | def __eq__(self, other): 30 | firstnum = self.num * other.den 31 | secondnum = other.num * self.den 32 | 33 | return firstnum == secondnum 34 | 35 | x = Fraction(1,2) 36 | y = Fraction(2,3) 37 | print(x+y) 38 | print(x == y) 39 | -------------------------------------------------------------------------------- /chap01_intro/aName.py: -------------------------------------------------------------------------------- 1 | 2 | aName = input('Please enter your name: ') 3 | print("Your name in all capitals is", aName.upper(), "and has length", len(aName)) 4 | -------------------------------------------------------------------------------- /chap01_intro/activeCode10.py: -------------------------------------------------------------------------------- 1 | wordlist = ['cat','dog','rabbit'] 2 | 3 | print [ch for ch in "".join(['cat', 'dog', 'rabbit'])] 4 | 5 | alist = [word[i] for word in ['cat', 'dog', 'rabbit'] for i in range (len(word))] 6 | print alist 7 | 8 | print list(set(alist)) 9 | 10 | -------------------------------------------------------------------------------- /chap01_intro/activeCode7.py: -------------------------------------------------------------------------------- 1 | wordlist = ['cat', 'dog', 'rabbit'] 2 | letterlist = [] 3 | for aword in wordlist: 4 | for aletter in aword: 5 | letterlist.append(aletter) 6 | print(letterlist) 7 | -------------------------------------------------------------------------------- /chap01_intro/activeCode8.py: -------------------------------------------------------------------------------- 1 | wordlist = ['cat','dog','rabbit'] 2 | letterlist = [ ] 3 | for aword in wordlist: 4 | for aletter in aword: 5 | letterlist.append(aletter) 6 | print(letterlist) 7 | -------------------------------------------------------------------------------- /chap01_intro/activeCode9.py: -------------------------------------------------------------------------------- 1 | wordlist = ['cat', 'dog', 'rabbit'] 2 | letterlist = [] 3 | for aword in wordlist: 4 | for aletter in aword: 5 | if aletter not in letterlist: 6 | letterlist.append(aletter) 7 | print(letterlist) 8 | -------------------------------------------------------------------------------- /chap01_intro/andGate.py: -------------------------------------------------------------------------------- 1 | class AndGate(BinaryGate): 2 | 3 | def __init__(self,n): 4 | BinaryGate.__init__(self,n) 5 | 6 | def performGateLogic(self): 7 | 8 | a = self.getPinA() 9 | b = self.getPinB() 10 | if a==1 and b ==1: 11 | return 1 12 | else 13 | return 0 -------------------------------------------------------------------------------- /chap01_intro/binaryGate.py: -------------------------------------------------------------------------------- 1 | 2 | class BinaryGate(LogicGate): 3 | 4 | def __init__(self,n): 5 | LogicGate.__init__(self,n) 6 | 7 | self.pinA = None 8 | self.pinB = None 9 | 10 | def getPinA(self): 11 | if self.pinA == None: 12 | return int(input("Enter Pin A input for gete " + self.getLabel()+"-->")) 13 | else: 14 | return self.pinA.getFrom().getOutput() 15 | 16 | def getPinB(self): 17 | return int(input("Enter Pin B input for gate " + self.getLabel()+"-->")) 18 | 19 | def setNextPin(self,source): 20 | if self.pinA == None: 21 | self.pinA = source 22 | else: 23 | if self.pinB == None: 24 | self.pinB = source 25 | else: 26 | rails RuntimeError("Error: NO EMPTY PINS") 27 | -------------------------------------------------------------------------------- /chap01_intro/connector.py: -------------------------------------------------------------------------------- 1 | class Connector: 2 | 3 | def __init__(self, fgate, tgate): 4 | self.fromgate = fgate 5 | self.togate = tgate 6 | 7 | tgate.setNextPin(self) 8 | 9 | def getFrom(self): 10 | return self.fromgate 11 | 12 | def getTo(self): 13 | return self.togate 14 | -------------------------------------------------------------------------------- /chap01_intro/listing1.py: -------------------------------------------------------------------------------- 1 | 2 | def squareroot(n): 3 | root = n/2.0 #initial guess will be 1/2 of n 4 | for k in range(20): 5 | root = (1.0/2.0) * (root + (n / root)) 6 | 7 | return root 8 | 9 | print squareroot(9) 10 | 11 | print squareroot(4563) 12 | -------------------------------------------------------------------------------- /chap01_intro/logic.py~: -------------------------------------------------------------------------------- 1 | 2 | class LogicGate: 3 | 4 | def __init__(self,n): 5 | self.label = n 6 | self.output = None 7 | 8 | def getLabel(self): 9 | return self.label 10 | 11 | def getOutput(self): 12 | self.output = self.performGateLogic() 13 | return self.output 14 | 15 | -------------------------------------------------------------------------------- /chap01_intro/logicGate.py: -------------------------------------------------------------------------------- 1 | 2 | class LogicGate: 3 | 4 | def __init__(self,n): 5 | self.label = n 6 | self.output = None 7 | 8 | def getLabel(self): 9 | return self.label 10 | 11 | def getOutput(self): 12 | self.output = self.performGateLogic() 13 | return self.output 14 | 15 | 16 | -------------------------------------------------------------------------------- /chap01_intro/monkeys.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def attempt(strlen): 5 | alphabet = "abcdefghijklmnopqrstuvqxyz " 6 | value = "" 7 | for letter in range(strlen): 8 | value = value + alphabet[random.randrange(27)] 9 | 10 | return value 11 | 12 | def score(goal, teststring): 13 | numSame = 0 14 | for i in range(len(goal)): 15 | if goal[i] == teststring[i]: 16 | numSame = numSame + 1 17 | return numSame / len(goal) 18 | 19 | def main(): 20 | 21 | goalstring = "methinks it is like a weasel" 22 | newstring = attempt(28) 23 | bestscore = 0 24 | beststring = "" 25 | newscore = score(goalstring, newstring) 26 | loopcount = 0 27 | while newscore < 1: 28 | if newscore > bestscore: 29 | print (newscore, newstring) 30 | bestscore = newscore 31 | beststring = newstring 32 | newstring = attempt(28) 33 | newscore = score(goalstring, newstring) 34 | 35 | if loopcount % 1000000 == 0: 36 | print (bestscore, beststring) 37 | loopcount = loopcount + 1 38 | 39 | main() 40 | -------------------------------------------------------------------------------- /chap01_intro/my_math.py: -------------------------------------------------------------------------------- 1 | import math 2 | print math.sqrt(16) 3 | -------------------------------------------------------------------------------- /chap01_intro/unaryGate.py: -------------------------------------------------------------------------------- 1 | 2 | class UnaryGate(LogicGate): 3 | 4 | def __init__(self,n): 5 | LogicGate.__init__(self,n) 6 | 7 | self.pin = None 8 | 9 | def getPin(self): 10 | return int(input("Enter Pin input for gate " + self.getLabel()+"-->")) 11 | 12 | -------------------------------------------------------------------------------- /chap02_analysis/listing2.py: -------------------------------------------------------------------------------- 1 | 2 | a = 5 3 | b = 6 4 | c = 10 5 | 6 | for i in range(n): 7 | for j in range(n): 8 | x = i * i 9 | y = j * j 10 | z = i * j 11 | 12 | for k in range(n): 13 | w = a * k + 45 14 | v = b * b 15 | 16 | d = 33 17 | 18 | -------------------------------------------------------------------------------- /chap02_analysis/listing3.py: -------------------------------------------------------------------------------- 1 | import timeit 2 | 3 | def test1(): 4 | l = [] 5 | for i in range(1000): 6 | l = l + [i] 7 | 8 | def test2(): 9 | l = [] 10 | for i in range(1000): 11 | l.append(i) 12 | 13 | def test3(): 14 | l = [i for i in range(1000)] 15 | 16 | def test4(): 17 | l = list(range(1000)) 18 | 19 | t1 = Timer("test1()", "from __main__ import test1") 20 | print("concat ",t1.timeit(number=1000), "milliseconds") 21 | -------------------------------------------------------------------------------- /chap02_analysis/quickSort.py: -------------------------------------------------------------------------------- 1 | 2 | def qsort1(list): 3 | """Quicksort using list comprehensions""" 4 | if list == []: 5 | return [] 6 | else: 7 | pivot = list[0] 8 | lesser = qsort1([x for x in list[1:] if x < pivot]) 9 | greater = qsort1([x for x in list[1:] if x >= pivot]) 10 | return lesser + [pivot] + greater 11 | 12 | def qsort2(list): 13 | """Quicksort using a partitoning function""" 14 | if list == []: 15 | return [] 16 | else: 17 | pivot = list[0] 18 | lesser, equal, greater = partition(list[1:], [], [pivot], []) 19 | return qsort2(lesser) + equal + qsort2(greater) 20 | 21 | # def partition(list, l, e, g): 22 | # """Recursive Partition""" 23 | # if list == []: 24 | # return (l, e, g) 25 | # else: 26 | # head = list[0] 27 | # if head < e[0]: 28 | # return partition(list[1:], l + [head], e, g) 29 | # elif head > e[0]: 30 | # return partition(list[1:], l, e, g + [head]) 31 | # else: 32 | # return partition(list[1:], l, e + [head], g) 33 | 34 | def partition(list, l, e, g): 35 | while list != []: 36 | head = list.pop(0) 37 | if head < e[0]: 38 | l = [head] + l 39 | elif head > e[0]: 40 | g = [head] + g 41 | else: 42 | e = [head] + g 43 | return (l, e, g) 44 | 45 | 46 | 47 | numbers = [5,33,6,2,4,7,8,9,12,41,25,64,57,86,79,1] 48 | 49 | 50 | print(numbers) 51 | print(qsort1(numbers)) 52 | 53 | 54 | -------------------------------------------------------------------------------- /chap02_analysis/randSelect.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def qnth(sample, n): 4 | pivot = sample[0] 5 | below = [s for s in sample if s < pivot] 6 | above = [s for s in sample if s > pivot] 7 | i, j = len(below), len(sample)-len(above) 8 | 9 | if n < i: 10 | return qnth(below, n) 11 | elif n >= j: 12 | return qnth(above, n-j) 13 | else: 14 | return pivot 15 | 16 | 17 | if __name__ == "__main__": 18 | import random 19 | n, mid = 2048, 7 20 | sample = [random.random() for _ in range(n)] 21 | partial = qnth(sample,mid) 22 | # sample.sort(); sorted = sample[mid] 23 | # print(partial, sorted, partial == sorted) 24 | print(partial) 25 | 26 | -------------------------------------------------------------------------------- /chap02_analysis/selfCheck1.py: -------------------------------------------------------------------------------- 1 | import time 2 | from random import randrange 3 | 4 | myList1 = [4,5,2,1,6,7,8,9,] 5 | myList2 = [0,1,2,3,4,5,6,7,8] 6 | 7 | def findMin(alist): 8 | overallmin = alist[0] 9 | for i in alist: 10 | issmallest = True 11 | for j in alist: 12 | if i > j: 13 | issmallest = False 14 | if issmallest: 15 | overallmin = i 16 | return overallmin 17 | 18 | 19 | def findMin2(alist): 20 | minsofar = alist[0] 21 | for i in alist: 22 | if i < minsofar: 23 | minsofar = i 24 | return minsofar 25 | 26 | 27 | for listSize in range(1000,10001,1000): 28 | alist = [randrange(100000) for x in range(listSize)] 29 | start = time.time() 30 | print(findMin(alist)) 31 | end = time.time() 32 | print("size: %d time: %f" % (listSize, end-start)) 33 | 34 | for listSize2 in range(1000,10001,1000): 35 | alist = [randrange(100000) for x in range(listSize2)] 36 | start = time.time() 37 | print(findMin2(alist)) 38 | end = time.time() 39 | print("size: %d time: %f" % (listSize2, end-start)) 40 | -------------------------------------------------------------------------------- /chap02_analysis/sumOf.py: -------------------------------------------------------------------------------- 1 | 2 | def sumOfN(n): 3 | theSum = 0 4 | for i in range(1,n+1): 5 | theSum = theSum + i 6 | 7 | return theSum 8 | 9 | 10 | print(sumOfN(10)) 11 | -------------------------------------------------------------------------------- /chap02_analysis/sumOf.py~: -------------------------------------------------------------------------------- 1 | 2 | def sumOfN(n): 3 | theSum = 0 4 | for i in range(1,n+1): 5 | theSum = theSum + i 6 | 7 | return theSum 8 | 9 | 10 | print(sumOfN(10)) 11 | -------------------------------------------------------------------------------- /chap02_analysis/sumOfN2.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def sumOfN2(n): 4 | start = time.time() 5 | 6 | theSum = 0 7 | for i in range(1,n+1): 8 | theSum = theSum + i 9 | 10 | end = time.time() 11 | 12 | return theSum,end-start 13 | 14 | def sumOfN3(n): 15 | start = time.time() 16 | 17 | theSum = (n*(n+1))/2 18 | 19 | end = time.time() 20 | return theSum, end-start 21 | 22 | 23 | 24 | n = 10000000 25 | 26 | for i in range(5): 27 | print("Sum is %d required %10.7f seconds "%sumOfN2(n)) 28 | 29 | print("------") 30 | 31 | for i in range(5): 32 | print("Sum id %d required %10.7f seconds " % sumOfN3(n)) 33 | -------------------------------------------------------------------------------- /chap02_analysis/sumOfN2.py~: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def sumOfN2(n): 4 | start = time.time() 5 | 6 | theSum = 0 7 | for i in range(1,n+1): 8 | theSum = theSum + i 9 | 10 | end = time.time() 11 | 12 | return theSum,end-start 13 | 14 | print (sumOfN2(10)) 15 | -------------------------------------------------------------------------------- /chap03_data_structures/__pycache__/stack.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap03_data_structures/__pycache__/stack.cpython-32.pyc -------------------------------------------------------------------------------- /chap03_data_structures/baseConverter.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def baseConverter(decNumber,base): 23 | digits = "0123456789ABCDEFGH" 24 | 25 | remstack = Stack() 26 | 27 | while decNumber > 0: 28 | rem = decNumber % base 29 | remstack.push(rem) 30 | decNumber = decNumber // base 31 | 32 | newString = "" 33 | while not remstack.isEmpty(): 34 | newString = newString + digits[remstack.pop()] 35 | 36 | return newString 37 | 38 | print(baseConverter(25,2)) 39 | print(baseConverter(25,16)) 40 | print(baseConverter(25,8)) 41 | print(baseConverter(256,16)) 42 | -------------------------------------------------------------------------------- /chap03_data_structures/deque.py: -------------------------------------------------------------------------------- 1 | 2 | class Deque: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def addFront(self, item): 10 | self.items.append(item) 11 | 12 | def addRear(self, item): 13 | self.items.insert(0,item) 14 | 15 | def removeFront(self): 16 | return self.items.pop() 17 | 18 | def removeRear(self): 19 | return self.items.pop(0) 20 | 21 | def size(self): 22 | return len(self.items) 23 | 24 | d = Deque() 25 | print(d.isEmpty()) 26 | d.addRear(4) 27 | d.addRear('dog') 28 | d.addFront('cat') 29 | d.addFront(True) 30 | print(d.size()) 31 | print(d.isEmpty()) 32 | d.addRear(8.4) 33 | print(d.removeRear()) 34 | print(d.removeFront()) 35 | -------------------------------------------------------------------------------- /chap03_data_structures/divideBy2.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def divideBy2(decNumber): 23 | remstack = Stack() 24 | 25 | while decNumber > 0: 26 | rem = decNumber % 2 27 | remstack.push(rem) 28 | decNumber = decNumber // 2 29 | 30 | binString = "" 31 | while not remstack.isEmpty(): 32 | binString = binString + str(remstack.pop()) 33 | 34 | return binString 35 | 36 | print(divideBy2(42)) 37 | -------------------------------------------------------------------------------- /chap03_data_structures/hotPotato.py: -------------------------------------------------------------------------------- 1 | 2 | class Queue: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def enqueue(self, item): 10 | self.items.insert(0,item) 11 | 12 | def dequeue(self): 13 | return self.items.pop() 14 | 15 | def size(self): 16 | return len(self.items) 17 | 18 | 19 | def hotPotato(namelist, num): 20 | simqueue = Queue() 21 | for name in namelist: 22 | simqueue.enqueue(name) 23 | 24 | while simqueue.size() > 1: 25 | for i in range(num): 26 | simqueue.enqueue(simqueue.dequeue()) 27 | 28 | simqueue.dequeue() 29 | 30 | return simqueue.dequeue() 31 | 32 | print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7)) 33 | -------------------------------------------------------------------------------- /chap03_data_structures/infixToPostfix.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def infixToPostfix(infixexpr): 23 | prec = {} 24 | prec["*"] = 3 25 | prec["/"] = 3 26 | prec["+"] = 2 27 | prec["-"] = 2 28 | prec["("] = 1 29 | opStack = Stack() 30 | postfixList = [] 31 | tokenList = infixexpr.split() 32 | 33 | for token in tokenList: 34 | if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": 35 | postfixList.append(token) 36 | elif token == '(': 37 | opStack.push(token) 38 | elif token == ')': 39 | topToken = opStack.pop() 40 | while topToken != '(': 41 | postfixList.append(topToken) 42 | topToken = opStack.pop() 43 | else: 44 | while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]): 45 | postfixList.append(opStack.pop()) 46 | opStack.push(token) 47 | 48 | while not opStack.isEmpty(): 49 | postfixList.append(opStack.pop()) 50 | return " ".join(postfixList) 51 | 52 | print(infixToPostfix("A * B + C * D")) 53 | print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) 54 | 55 | print(infixToPostfix("( A + B ) * ( C + D )")) 56 | print(infixToPostfix("( A + B ) * C")) 57 | print(infixToPostfix("A + B * C")) 58 | 59 | -------------------------------------------------------------------------------- /chap03_data_structures/infixToPostfix2.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def infixToPostfix(infixexpr): 23 | prec = {} 24 | prec["^"] = 4 25 | prec["*"] = 3 26 | prec["/"] = 3 27 | prec["+"] = 2 28 | prec["-"] = 2 29 | prec["("] = 1 30 | opStack = Stack() 31 | postfixList = [] 32 | tokenList = infixexpr.split() 33 | 34 | for token in tokenList: 35 | if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": 36 | postfixList.append(token) 37 | elif token == '(': 38 | opStack.push(token) 39 | elif token == ')': 40 | topToken = opStack.pop() 41 | while topToken != '(': 42 | postfixList.append(topToken) 43 | topToken = opStack.pop() 44 | else: 45 | while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]): 46 | postfixList.append(opStack.pop()) 47 | opStack.push(token) 48 | 49 | while not opStack.isEmpty(): 50 | postfixList.append(opStack.pop()) 51 | return " ".join(postfixList) 52 | 53 | print(infixToPostfix("5 * 3 ^ ( 4 - 2 )")) 54 | -------------------------------------------------------------------------------- /chap03_data_structures/palChecker.py: -------------------------------------------------------------------------------- 1 | 2 | class Deque: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def addFront(self, item): 10 | self.items.append(item) 11 | 12 | def addRear(self, item): 13 | self.items.insert(0,item) 14 | 15 | def removeFront(self): 16 | return self.items.pop() 17 | 18 | def removeRear(self): 19 | return self.items.pop(0) 20 | 21 | def size(self): 22 | return len(self.items) 23 | 24 | d = Deque() 25 | 26 | def palchecker(aString): 27 | chardeque = Deque() 28 | 29 | for ch in aString: 30 | chardeque.addRear(ch) 31 | 32 | stillEqual = True 33 | 34 | while chardeque.size() > 1 and stillEqual: 35 | first = chardeque.removeFront() 36 | last = chardeque.removeRear() 37 | if first != last: 38 | stillEqual = False 39 | 40 | return stillEqual 41 | 42 | print(palchecker("lsdkjfskf")) 43 | print(palchecker("radar")) 44 | -------------------------------------------------------------------------------- /chap03_data_structures/postfixEval.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def postfixEval(postfixExpr): 23 | operandStack = Stack() 24 | tokenList = postfixExpr.split() 25 | 26 | for token in tokenList: 27 | if token in "0123456789": 28 | operandStack.push(int(token)) 29 | else: 30 | operand2 = operandStack.pop() 31 | operand1 = operandStack.pop() 32 | result = doMath(token,operand1,operand2) 33 | operandStack.push(result) 34 | return operandStack.pop() 35 | 36 | def doMath(op, op1, op2): 37 | if op == "*": 38 | return op1 * op2 39 | elif op == "/": 40 | return op1 / op2 41 | elif op == "+": 42 | return op1 + op2 43 | else: 44 | return op1 - op2 45 | 46 | 47 | 48 | 49 | print(postfixEval('7 8 + 3 2 + /')) 50 | 51 | -------------------------------------------------------------------------------- /chap03_data_structures/queue.py: -------------------------------------------------------------------------------- 1 | 2 | class Queue: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def enqueue(self, item): 10 | self.items.insert(0,item) 11 | 12 | def dequeue(self): 13 | return self.items.pop() 14 | 15 | def size(self): 16 | return len(self.items) 17 | 18 | 19 | q = Queue() 20 | print(q.isEmpty()) 21 | 22 | q.enqueue(4) 23 | q.enqueue('dog') 24 | q.enqueue(True) 25 | 26 | print(q.size()) 27 | print(q.isEmpty()) 28 | 29 | q.enqueue(8.4) 30 | 31 | print(q.dequeue()) 32 | print(q.dequeue()) 33 | 34 | print(q.size()) 35 | 36 | -------------------------------------------------------------------------------- /chap03_data_structures/revstring.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | 22 | def revstring(mystr): 23 | s = Stack() 24 | rev = [] 25 | for c in mystr: 26 | s.push(c) 27 | 28 | while not s.isEmpty(): 29 | rev.append(s.pop()) 30 | return "".join(rev) 31 | 32 | testString = "This is the test string. It is pretty good" 33 | 34 | print (revstring(testString)) 35 | 36 | -------------------------------------------------------------------------------- /chap03_data_structures/stack.py: -------------------------------------------------------------------------------- 1 | 2 | class Stack: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def push(self, item): 10 | self.items.append(item) 11 | 12 | def pop(self): 13 | return self.items.pop() 14 | 15 | def peek(self): 16 | return self.items[len(self.items)-1] 17 | 18 | def size(self): 19 | return len(self.items) 20 | 21 | s=Stack() 22 | 23 | print(s.isEmpty()) 24 | s.push(4) 25 | s.push('dog') 26 | print(s.peek()) 27 | s.push(True) 28 | print(s.size()) 29 | print(s.isEmpty()) 30 | s.push(8.4) 31 | print(s.pop()) 32 | print(s.pop()) 33 | print(s.size()) 34 | -------------------------------------------------------------------------------- /chap04_recursion/change.py: -------------------------------------------------------------------------------- 1 | def recMC(coinValueList, change): 2 | minCoins = change 3 | if change in coinValueList: 4 | return 1 5 | else: 6 | for i in [c for c in coinValueList if c <= change]: 7 | numCoins = 1 + recMC(coinValueList, change-i) 8 | if numCoins < minCoins: 9 | minCoins = numCoins 10 | return minCoins 11 | 12 | print(recMC([1,5,10,25],63)) -------------------------------------------------------------------------------- /chap04_recursion/changeDP.py: -------------------------------------------------------------------------------- 1 | def recDC(coinValueList, change,knownResults): 2 | minCoins = change 3 | if change in coinValueList: 4 | knownResults[change] = 1 5 | return 1 6 | elif knownResults[change] > 0: 7 | return knownResults[change] 8 | else: 9 | for i in [c for c in coinValueList if c <= change]: 10 | numCoins = 1 + recDC(coinValueList, change-i,knownResults) 11 | if numCoins < minCoins: 12 | minCoins = numCoins 13 | knownResults[change] = minCoins 14 | return minCoins 15 | 16 | print(recDC([1,5,10,25],63,[0]*64)) -------------------------------------------------------------------------------- /chap04_recursion/fact.py: -------------------------------------------------------------------------------- 1 | 2 | def fact(n): 3 | if n <= 1: 4 | return 1 5 | else: 6 | return n * fact(n -1) 7 | 8 | 9 | 10 | def main(): 11 | num = 5 12 | print(fact(num)) 13 | 14 | 15 | if __name__ == "__main__": 16 | main() 17 | -------------------------------------------------------------------------------- /chap04_recursion/fact.py~: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def main(): 5 | 6 | print "main" 7 | num = 3 8 | print(fact(3)) 9 | 10 | 11 | if __name__ == "__main__": 12 | main() 13 | -------------------------------------------------------------------------------- /chap04_recursion/listSum.py: -------------------------------------------------------------------------------- 1 | 2 | def listsum(numList): 3 | theSum = 0 4 | for i in numList: 5 | theSum = theSum + i 6 | return theSum 7 | 8 | def main(): 9 | print(listsum([1,3,5,7,9])) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /chap04_recursion/listSum.py~: -------------------------------------------------------------------------------- 1 | 2 | def listsum(numList): 3 | theSum = 0 4 | for i in numList: 5 | theSum = theSum + i 6 | return theSum 7 | 8 | def main(): 9 | print(listsum([,1,3,5,7,9])) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /chap04_recursion/listSum2.py: -------------------------------------------------------------------------------- 1 | 2 | def listsum(numList): 3 | if len(numList) == 1: 4 | return numList[0] 5 | else: 6 | return numList[0] + listsum(numList[1:]) 7 | 8 | def main(): 9 | print(listsum([1,3,5,7,9])) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /chap04_recursion/listSum2.py~: -------------------------------------------------------------------------------- 1 | 2 | def listsum(numList): 3 | theSum = 0 4 | for i in numList: 5 | theSum = theSum + i 6 | return theSum 7 | 8 | def main(): 9 | print(listsum([1,3,5,7,9])) 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /chap04_recursion/maze2.txt: -------------------------------------------------------------------------------- 1 | +++++++++++++++++++++++ 2 | + + ++ ++ + 3 | + + + +++ + +++ 4 | + + + ++ ++++ + +++ 5 | +++ ++++++ +++ + ++ 6 | + ++ ++ ++ 7 | +++++ ++++++ +++++ ++ 8 | + + +++++++ + ++ 9 | + +++++++ S + ++ 10 | + + ++++ 11 | ++++++++++++++++++ ++++ -------------------------------------------------------------------------------- /chap04_recursion/pal.py: -------------------------------------------------------------------------------- 1 | 2 | def helper(s1, s2): 3 | if s1 == s2: 4 | return True 5 | return False 6 | 7 | def removeWhite(s): 8 | excludes = ("'", ',', ';', '.', ' ') 9 | return "".join(ch.upper() for ch in s if ch not in excludes) 10 | 11 | def isPal(s): 12 | s = removeWhite(s) 13 | if len(s) <= 1: 14 | return True 15 | else: 16 | return helper(s[0],s[-1]) and isPal(s[1:-1]) 17 | 18 | 19 | print(isPal("reviled did I live, said I, as evil I did deliver")) 20 | 21 | print(isPal("Go hang a salami; I'm a lasagna hog.")) 22 | print(isPal("radar")) 23 | print(isPal("")) 24 | -------------------------------------------------------------------------------- /chap04_recursion/pal.py~: -------------------------------------------------------------------------------- 1 | 2 | def helper(s1, s2): 3 | if s1 == s2: 4 | return True 5 | return False 6 | 7 | def isPal(s): 8 | if len(s) <= 2: 9 | return helper(s[0],s[-1]) 10 | else: 11 | return helper(s[0],s[-1]) + isPal(s[1:-2]) 12 | 13 | 14 | print(isPal("aba")) 15 | -------------------------------------------------------------------------------- /chap04_recursion/reverse.py: -------------------------------------------------------------------------------- 1 | 2 | def reverse(s): 3 | if len(s) <= 1: 4 | return s[0] 5 | else: 6 | return reverse(s[1:]) + s[0] 7 | 8 | print(reverse("hello")) 9 | -------------------------------------------------------------------------------- /chap04_recursion/reverse.py~: -------------------------------------------------------------------------------- 1 | 2 | def reverse(s): 3 | if len(s) <= 1: 4 | return s 5 | else: 6 | return reverse(s[1:]) + s[0] 7 | 8 | print reverse("hello") 9 | -------------------------------------------------------------------------------- /chap04_recursion/spMakeChange.py: -------------------------------------------------------------------------------- 1 | def dpMakeChange(coinValueList,change,minCoins,coinsUsed): 2 | for cents in range(change+1): 3 | coinCount = cents 4 | newCoin = 1 5 | for j in [c for c in coinValueList if c <= cents]: 6 | if minCoins[cents-j] + 1 < coinCount: 7 | coinCount = minCoins[cents-j] + 1 8 | newCoin = j 9 | minCoins[cents] = coinCount 10 | coinsUsed[cents] = newCoin 11 | return minCoins[change] 12 | 13 | def printCoins(coinsUsed,change): 14 | coin = change 15 | while coin > 0: 16 | thisCoin = coinsUsed[coin] 17 | print(thisCoin) 18 | coin = coin - thisCoin 19 | 20 | def main(): 21 | amnt = 63 22 | clist = [1,5,10,21,25] 23 | coinsUsed = [0]*(amnt+1) 24 | coinCount = [0]*(amnt+1) 25 | 26 | print("Making change for", amnt,"requires") 27 | print(dpMakeChange(clist,amnt,coinCount,coinsUsed),"coins") 28 | print("They are:") 29 | printCoins(coinsUsed,amnt) 30 | print("The used list is as follows:") 31 | print(coinsUsed) 32 | 33 | main() 34 | 35 | -------------------------------------------------------------------------------- /chap04_recursion/toStr.py: -------------------------------------------------------------------------------- 1 | 2 | def toStr(n,base): 3 | convertString = "0123456789ABCDEF" 4 | if n < base: 5 | return convertString[n] 6 | else: 7 | return toStr(n//base,base) + convertString[n%base] 8 | 9 | print(toStr(1453,16)) 10 | -------------------------------------------------------------------------------- /chap04_recursion/tower.py: -------------------------------------------------------------------------------- 1 | 2 | def moveTower(height,fromPole, toPole, withPole): 3 | if height >= 1: 4 | moveTower(height-1,fromPole,withPole,toPole) 5 | moveDisk(fromPole,toPole) 6 | moveTower(height-1,withPole,toPole,fromPole) 7 | 8 | def moveDisk(fp,tp): 9 | print("moving disk from",fp,"to",tp) 10 | 11 | moveTower(30,"A","B","C") 12 | -------------------------------------------------------------------------------- /chap04_recursion/tower.py~: -------------------------------------------------------------------------------- 1 | 2 | def moveTower(height,fromPole, toPole, withPole): 3 | if height >= 1: 4 | moveTower(height-1,fromPole,withPole,toPole) 5 | moveDisk(fromPole,toPole) 6 | moveTower(height-1,withPole,toPole,fromPole) 7 | 8 | -------------------------------------------------------------------------------- /chap04_recursion/triangle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def drawTriangle(points,color,myTurtle): 4 | myTurtle.fillcolor(color) 5 | myTurtle.up() 6 | myTurtle.goto(points[0][0],points[0][1]) 7 | myTurtle.down() 8 | myTurtle.begin_fill() 9 | myTurtle.goto(points[1][0],points[1][1]) 10 | myTurtle.goto(points[2][0],points[2][1]) 11 | myTurtle.goto(points[0][0],points[0][1]) 12 | myTurtle.end_fill() 13 | 14 | def getMid(p1,p2): 15 | return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) 16 | 17 | def sierpinski(points,degree,myTurtle): 18 | colormap = ['blue', 'red','green','white','yellow','violet','orange'] 19 | drawTriangle(points,colormap[degree],myTurtle) 20 | if degree > 0: 21 | sierpinski([points[0], 22 | getMid(points[0], points[1]), 23 | getMid(points[0], points[2])], 24 | degree-1, myTurtle) 25 | sierpinski([points[1], 26 | getMid(points[0], points[1]), 27 | getMid(points[1], points[2])], 28 | degree-1, myTurtle) 29 | sierpinski([points[2], 30 | getMid(points[2], points[1]), 31 | getMid(points[0], points[2])], 32 | degree-1, myTurtle) 33 | 34 | def main(): 35 | myTurtle = turtle.Turtle() 36 | myWin = turtle.Screen() 37 | myPoints = [[-100,-50],[0,100],[100,-50]] 38 | sierpinski(myPoints,3,myTurtle) 39 | myWin.exitonclick() 40 | 41 | 42 | main() 43 | -------------------------------------------------------------------------------- /chap04_recursion/turtle1.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | myTurtle = turtle.Turtle() 4 | myWin = turtle.Screen() 5 | 6 | def drawSpiral(myTurtle, lineLen): 7 | if lineLen > 0: 8 | myTurtle.forward(lineLen) 9 | myTurtle.right(90) 10 | drawSpiral(myTurtle,lineLen-5) 11 | 12 | drawSpiral(myTurtle,100) 13 | myWin.exitonclick() 14 | -------------------------------------------------------------------------------- /chap04_recursion/turtle1.py~: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | myTurtle = turtle.Turtle() 4 | myWin = turtle.Screen() 5 | 6 | -------------------------------------------------------------------------------- /chap04_recursion/turtleTree.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def tree(branchLen,t): 4 | if branchLen > 5: 5 | t.forward(branchLen) 6 | t.right(20) 7 | tree(branchLen-15,t) 8 | t.left(40) 9 | tree(branchLen-15,t) 10 | t.right(20) 11 | t.backward(branchLen) 12 | 13 | def main(): 14 | t = turtle.Turtle() 15 | myWin = turtle.Screen() 16 | t.left(90) 17 | t.up() 18 | t.backward(100) 19 | t.down() 20 | t.color("green") 21 | tree(75,t) 22 | myWin.exitonclick() 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /chap04_recursion/turtleTree.py~: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | myTurtle = turtle.Turtle() 4 | myWin = turtle.Screen() 5 | 6 | def drawSpiral(myTurtle, lineLen): 7 | if lineLen > 0: 8 | myTurtle.forward(lineLen) 9 | myTurtle.right(90) 10 | drawSpiral(myTurtle,lineLen-5) 11 | 12 | drawSpiral(myTurtle,100) 13 | myWin.exitonclick() 14 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/binarySearch.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist, item): 2 | first = 0 3 | last = len(alist)-1 4 | found = False 5 | 6 | while first<=last and not found: 7 | midpoint = (first+last)//2 8 | if alist[midpoint] == item: 9 | found = True 10 | else: 11 | if item < alist[midpoint]: 12 | last = midpoint-1 13 | else: 14 | first = midpoint+1 15 | 16 | return found 17 | 18 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] 19 | print(binarySearch(testlist, 3)) 20 | print(binarySearch(testlist, 13)) 21 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/binarySearchRec.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist,item): 2 | if len(alist) == 0: 3 | return False 4 | else: 5 | midpoint = len(alist)//2 6 | if alist[midpoint] == item: 7 | return True 8 | else: 9 | if item < alist[midpoint]: 10 | return binarySearch(alist[:midpoint], item) 11 | else: 12 | return binarySearch(alist[midpoint+1:], item) 13 | 14 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] 15 | print(binarySearch(testlist, 3)) 16 | print(binarySearch(testlist, 13)) 17 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/bubbleSort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(alist): 2 | for passnum in range(len(alist)-1,0,-1): 3 | for i in range(passnum): 4 | if alist[i]>alist[i+1]: 5 | temp = alist[i] 6 | alist[i] = alist[i+1] 7 | alist[i+1] = temp 8 | 9 | alist = [54,26,93,17,77,31,44,55,20] 10 | bubbleSort(alist) 11 | print(alist) 12 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/hash.py: -------------------------------------------------------------------------------- 1 | def hash(astring, tablesize): 2 | sum = 0 3 | for pos in range(len(astring)): 4 | sum = sum + (pos+1) * ord(astring[pos]) 5 | 6 | return sum%tablesize 7 | 8 | print(hash('abba', 11)) 9 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/insertionSort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(alist): 2 | for index in range(1,len(alist)): 3 | 4 | currentvalue = alist[index] 5 | position = index 6 | 7 | while position>0 and alist[position-1]>currentvalue: 8 | alist[position]=alist[position-1] 9 | position = position-1 10 | 11 | alist[position] = currentvalue 12 | 13 | alist = [54,26,93,17,77,31,44,55,20] 14 | insertionSort(alist) 15 | print(alist) 16 | 17 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/mergeSort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(alist): 2 | print("Splitting ",alist) 3 | if len(alist)>1: 4 | mid = len(alist)//2 5 | lefthalf = alist[:mid] 6 | righthalf = alist[mid:] 7 | 8 | mergeSort(lefthalf) 9 | mergeSort(righthalf) 10 | 11 | i=0 12 | j=0 13 | k=0 14 | while i item: 10 | stop = True 11 | else: 12 | pos = pos+1 13 | 14 | return found 15 | 16 | testlist = [0,1,2,8,13,17,19,32,42,] 17 | print(orderedSequentialSearch(testlist,3)) 18 | print(orderedSequentialSearch(testlist,13)) 19 | 20 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/quickSort.py: -------------------------------------------------------------------------------- 1 | def quickSort(alist): 2 | quickSortHelper(alist,0,len(alist)-1) 3 | 4 | def quickSortHelper(alist,first,last): 5 | if first= pivotvalue and rightmark >= leftmark: 25 | rightmark = rightmark -1 26 | 27 | if rightmark < leftmark: 28 | done = True 29 | else: 30 | temp = alist[leftmark] 31 | alist[leftmark] = alist[rightmark] 32 | alist[rightmark] = temp 33 | 34 | temp = alist[first] 35 | alist[first] = alist[rightmark] 36 | alist[rightmark] = temp 37 | 38 | 39 | return rightmark 40 | 41 | alist = [54,26,93,17,77,31,44,55,20] 42 | quickSort(alist) 43 | print(alist) -------------------------------------------------------------------------------- /chap05_sorting_and_searching/selectionSort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(alist): 2 | for fillslot in range(len(alist)-1,0,-1): 3 | positionOfMax=0 4 | for location in range(1,fillslot+1): 5 | if alist[location]>alist[positionOfMax]: 6 | positionOfMax = location 7 | 8 | temp = alist[fillslot] 9 | alist[fillslot] = alist[positionOfMax] 10 | alist[positionOfMax] = temp 11 | 12 | alist = [54,26,93,17,77,31,44,55,20] 13 | selectionSort(alist) 14 | print(alist) 15 | -------------------------------------------------------------------------------- /chap05_sorting_and_searching/sequentialSearch.py: -------------------------------------------------------------------------------- 1 | def sequentialSearch(alist, item): 2 | pos = 0 3 | found = False 4 | 5 | while pos < len(alist) and not found: 6 | if alist[pos] == item: 7 | found = True 8 | else: 9 | pos = pos + 1 10 | 11 | return found 12 | 13 | 14 | testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] 15 | print(sequentialSearch(testlist, 3)) 16 | print(sequentialSearch(testlist, 13)) -------------------------------------------------------------------------------- /chap05_sorting_and_searching/shellSort.py: -------------------------------------------------------------------------------- 1 | def shellSort(alist): 2 | sublistcount = len(alist)//2 3 | while sublistcount > 0: 4 | 5 | for startposition in range(sublistcount): 6 | gapInsertionSort(alist,startposition,sublistcount) 7 | 8 | print("After increments of size",sublistcount,"The list is",alist) 9 | 10 | sublistcount = sublistcount // 2 11 | 12 | def gapInsertionSort(alist,start,gap): 13 | for i in range(start+gap,len(alist),gap): 14 | 15 | currentvalue = alist[i] 16 | position = i 17 | 18 | while position>=gap and alist[position-gap]>currentvalue: 19 | alist[position]=alist[position-gap] 20 | position = position-gap 21 | 22 | alist[position]=currentvalue 23 | 24 | alist = [54,26,93,17,77,31,44,55,20] 25 | shellSort(alist) 26 | print(alist) -------------------------------------------------------------------------------- /chap05_sorting_and_searching/shortBubbleSort.py: -------------------------------------------------------------------------------- 1 | def shortBubbleSort(alist): 2 | exchanges = True 3 | passnum = len(alist)-1 4 | while passnum > 0 and exchanges: 5 | exchanges = False 6 | for i in range(passnum): 7 | if alist[i]> alist[i+1]: 8 | exchanges = True 9 | temp = alist[i] 10 | alist[i] = alist[i+1] 11 | alist[i+1] = temp 12 | passnum = passnum-1 13 | 14 | alist=[20,30,40,90,50,60,70,80,100,110] 15 | shortBubbleSort(alist) 16 | 17 | print(alist) 18 | 19 | -------------------------------------------------------------------------------- /chap06_trees/1-BinaryTree/binaryTreeExample.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is an example of a BinaryTree data structure 3 | built as a class 4 | 5 | This example will only work if the rootObj passed into the 6 | class is a python primitive data type. 7 | ''' 8 | 9 | class BinaryTree: 10 | def __init__(self,rootObj): 11 | self.key = rootObj 12 | self.leftChild = None 13 | self.rightChild = None 14 | 15 | def insertLeft(self,newNode): 16 | if self.leftChild == None: 17 | self.leftChild = BinaryTree(newNode) 18 | else: 19 | t = BinaryTree(newNode) 20 | t.leftChild = self.leftChild 21 | self.leftChild = t 22 | 23 | def insertRight(self,newNode): 24 | if self.rightChild == None: 25 | self.rightChild = BinaryTree(newNode) 26 | else: 27 | t = BinaryTree(newNode) 28 | t.rightChild = self.rightChild 29 | self.rightChild = t 30 | 31 | def getRightChild(self): 32 | return self.rightChild 33 | 34 | def getLeftChild(self): 35 | return self.leftChild 36 | 37 | def setRootVal(self,obj): 38 | self.key =obj 39 | 40 | def getRootVal(self): 41 | return self.key 42 | 43 | 44 | r = BinaryTree('a') 45 | print(r.getRootVal()) 46 | print(r.getLeftChild()) 47 | r.insertLeft('b') 48 | print(r.getLeftChild()) 49 | print(r.getLeftChild().getRootVal()) 50 | r.insertRight('c') 51 | print(r.getRightChild()) 52 | print(r.getRightChild().getRootVal()) 53 | r.getRightChild().setRootVal('hello') 54 | print(r.getRightChild().getRootVal()) 55 | 56 | -------------------------------------------------------------------------------- /chap06_trees/1-BinaryTree/binaryTreeLists.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This is an example of a binary tree data structure created with 3 | python lists as the underlying data structure. 4 | 5 | ''' 6 | 7 | def BinaryTree(r): 8 | return [r, [], []] 9 | 10 | def insertLeft(root,newBranch): 11 | t = root.pop(1) 12 | if len(t) > 1: 13 | root.insert(1,[newBranch,t,[]]) 14 | else: 15 | root.insert(1,[newBranch, [], []]) 16 | return root 17 | 18 | def insertRight(root,newBranch): 19 | t = root.pop(2) 20 | if len(t) > 1: 21 | root.insert(2,[newBranch,[],t]) 22 | else: 23 | root.insert(2,[newBranch,[],[]]) 24 | return root 25 | 26 | def getRootVal(root): 27 | return root[0] 28 | 29 | def setRootVal(root,newVal): 30 | root[0] = newVal 31 | 32 | def getLeftChild(root): 33 | return root[1] 34 | 35 | def getRightChild(root): 36 | return root[2] 37 | 38 | 39 | r = BinaryTree(3) 40 | insertLeft(r,4) 41 | insertLeft(r,5) 42 | insertRight(r,6) 43 | insertRight(r,7) 44 | l = getLeftChild(r) 45 | print(l) 46 | 47 | setRootVal(l,9) 48 | print(r) 49 | insertLeft(l,11) 50 | print(r) 51 | print(getRightChild(getRightChild(r))) 52 | 53 | 54 | b = BinaryTree('a') 55 | # Build up the left side of this tree 56 | insertLeft(b,'b') 57 | insertRight(getLeftChild(b),'d') 58 | 59 | # Build up the right side of this tree 60 | insertRight(b,'c') 61 | insertLeft(getRightChild(b),'e') 62 | insertRight(getRightChild(b),'f') 63 | 64 | print(b) 65 | -------------------------------------------------------------------------------- /chap06_trees/1-BinaryTree/myTree.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A very simple example of a binary tree created on a 3 | python list primitive data structure 4 | ''' 5 | myTree = ['a',['b',['d',[],[]],['e',[],[]]],['c',['f',[],[]],[]] ] 6 | print(myTree) 7 | print('left subtree = ', myTree[1]) 8 | print('root = ', myTree[0]) 9 | print('right subtree = ', myTree[2]) 10 | -------------------------------------------------------------------------------- /chap06_trees/2-BinaryTreeApplications-ParseTree/BinaryTree.py: -------------------------------------------------------------------------------- 1 | class BinaryTree: 2 | def __init__(self,rootObj): 3 | self.key = rootObj 4 | self.leftChild = None 5 | self.rightChild = None 6 | 7 | def insertLeft(self,newNode): 8 | if self.leftChild == None: 9 | self.leftChild = BinaryTree(newNode) 10 | else: 11 | t = BinaryTree(newNode) 12 | t.leftChild = self.leftChild 13 | self.leftChild = t 14 | 15 | def insertRight(self,newNode): 16 | if self.rightChild == None: 17 | self.rightChild = BinaryTree(newNode) 18 | else: 19 | t = BinaryTree(newNode) 20 | t.rightChild = self.rightChild 21 | self.rightChild = t 22 | 23 | def getRightChild(self): 24 | return self.rightChild 25 | 26 | def getLeftChild(self): 27 | return self.leftChild 28 | 29 | def setRootVal(self,obj): 30 | self.key =obj 31 | 32 | def getRootVal(self): 33 | return self.key 34 | 35 | def preorder(self): 36 | print(self.key) 37 | if self.leftChild: 38 | self.leftChild.preorder() 39 | if self.rightChild: 40 | self.rightChild.preorder() 41 | 42 | def postorder(self): 43 | if self.leftChild: 44 | self.leftChild.postorder() 45 | if self.rightChild: 46 | self.rightChild.postorder() 47 | print(self.key) -------------------------------------------------------------------------------- /chap06_trees/2-BinaryTreeApplications-ParseTree/Stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | return self.items == [] 7 | 8 | def push(self, item): 9 | self.items.append(item) 10 | 11 | def pop(self): 12 | return self.items.pop() 13 | 14 | def peek(self): 15 | return self.items[len(self.items)-1] 16 | 17 | def size(self): 18 | return len(self.items) -------------------------------------------------------------------------------- /chap06_trees/3-PriorityQueuesWithBinaryHeaps/BinHeap.py: -------------------------------------------------------------------------------- 1 | class BinHeap: 2 | def __init__(self): 3 | self.heapList = [0] 4 | self.currentSize = 0 5 | 6 | def percUp(self,i): 7 | while i // 2 > 0: 8 | if self.heapList[i] < self.heapList[i // 2]: 9 | tmp = self.heapList[i // 2] 10 | self.heapList[i // 2] = self.heapList[i] 11 | self.heapList[i] = tmp 12 | i = i // 2 13 | 14 | def percDown(self,i): 15 | while (i * 2) <= self.currentSize: 16 | mc = self.minChild(i) 17 | if self.heapList[i] >self.heapList[mc]: 18 | tmp = self.heapList[i] 19 | self.heapList[i] = self.heapList[mc] 20 | self.heapList[mc] = tmp 21 | i = mc 22 | 23 | def minChild(self,i): 24 | if i * 2 + 1 > self.currentSize: 25 | return i * 2 26 | else: 27 | if self.heapList[i*2] < self.heapList[i*2+1]: 28 | return i * 2 29 | else: 30 | return i * 2 + 1 31 | 32 | def insert(self,k): 33 | self.heapList.append(k) 34 | self.currentSize = self.currentSize + 1 35 | self.percUp(self.currentSize) 36 | 37 | def delMin(self): 38 | retval = self.heapList[1] 39 | self.heapList[1] = self.heapList[self.currentSize] 40 | self.currentSize = self.currentSize - 1 41 | self.heapList.pop() 42 | self.percDown(1) 43 | return retval 44 | 45 | 46 | def buildHeap(self,alist): 47 | i = len(alist) // 2 48 | self.currentSize = len(alist) 49 | self.heapList = [0] + alist[:] 50 | while (i > 0): 51 | self.percDown(i) 52 | i = i -1 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /chap06_trees/3-PriorityQueuesWithBinaryHeaps/testBinHeap.py: -------------------------------------------------------------------------------- 1 | from BinHeap import BinHeap 2 | 3 | bh = BinHeap() 4 | bh.buildHeap([9,5,6,2,3]) 5 | 6 | print(bh.delMin()) 7 | print(bh.delMin()) 8 | print(bh.delMin()) 9 | print(bh.delMin()) 10 | print(bh.delMin()) -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/BinarySearchTree.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/4-BinarySearchTree/BinarySearchTree.pyc -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/TreeNode.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/4-BinarySearchTree/TreeNode.pyc -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/TreeNode.py~: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | '''A node for the Binary Search Tree ''' 3 | 4 | def __init__(self,key,val,left=None,right=None,parent=None): 5 | self.key = key 6 | self.payload = val 7 | self.leftChild = left 8 | self.rightChild = right 9 | self.parent = parent 10 | 11 | def hasLeftChild(self): 12 | return self.leftChild 13 | 14 | def hasRightChild(self): 15 | return self.rightChild 16 | 17 | def isLeftChild(self): 18 | return self.parten and self.parent.leftChild == self 19 | 20 | def isRightChild(self): 21 | return self.parent and self.parent.rightChild == self 22 | 23 | def isRoot(self): 24 | return not self.parent 25 | 26 | def isLeaf(self): 27 | return not (rightChild or self.leftChild) 28 | 29 | def hasAnyChildren(self): 30 | return self.rightChild or self.leftChild 31 | 32 | def hasBothChildren(self): 33 | return self.rightChild and self.leftChild 34 | 35 | def replaceNodeData(self,key,value,lc,rc): 36 | self.key = key 37 | self.payload = value 38 | self.leftChild = lc 39 | self.rightChild = rc 40 | if self.hasLeftChild(): 41 | self.leftChild.parent = self 42 | if self.hasRightChild(): 43 | self.rightChild.parent = self 44 | 45 | def 46 | 47 | 48 | -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/__pycache__/BinarySearchTree.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/4-BinarySearchTree/__pycache__/BinarySearchTree.cpython-32.pyc -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/__pycache__/TreeNode.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/4-BinarySearchTree/__pycache__/TreeNode.cpython-32.pyc -------------------------------------------------------------------------------- /chap06_trees/4-BinarySearchTree/testBST.py: -------------------------------------------------------------------------------- 1 | from BinarySearchTree import BinarySearchTree 2 | 3 | mytree = BinarySearchTree() 4 | mytree[3]="red" 5 | mytree[4]="blue" 6 | mytree[6]="yellow" 7 | mytree[2]="at" 8 | 9 | print(mytree[6]) 10 | print(mytree[2]) -------------------------------------------------------------------------------- /chap06_trees/5-BalancedBinarySearchTrees/AvlTree.py~: -------------------------------------------------------------------------------- 1 | from BinarySearchTree import BinarySearchTree 2 | 3 | -------------------------------------------------------------------------------- /chap06_trees/5-BalancedBinarySearchTrees/BinarySearchTree.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/5-BalancedBinarySearchTrees/BinarySearchTree.pyc -------------------------------------------------------------------------------- /chap06_trees/5-BalancedBinarySearchTrees/TreeNode.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/5-BalancedBinarySearchTrees/TreeNode.pyc -------------------------------------------------------------------------------- /chap06_trees/__pycache__/BinHeap.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/__pycache__/BinHeap.cpython-32.pyc -------------------------------------------------------------------------------- /chap06_trees/__pycache__/BinaryTree.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/__pycache__/BinaryTree.cpython-32.pyc -------------------------------------------------------------------------------- /chap06_trees/__pycache__/Stack.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap06_trees/__pycache__/Stack.cpython-32.pyc -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Graph.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.vertList = {} 6 | self.numVertices = 0 7 | 8 | def addVertex(self,key): 9 | self.numVertices = self.numVertices + 1 10 | newVertex = Vertex(key) 11 | self.vertList[key] = newVertex 12 | return newVertex 13 | 14 | def getVertex(self,n): 15 | if n in self.vertList: 16 | return self.vertList[n] 17 | else: 18 | return None 19 | 20 | def __contains__(self,n): 21 | return n in self.vertList 22 | 23 | def addEdge(self,f,t,cost=0): 24 | if f not in self.vertList: 25 | nv = self.addVertex(f) 26 | if t not in self.vertList: 27 | nv = self.addVertex(t) 28 | self.vertList[f].addNeighbor(self.vertList[t], cost) 29 | 30 | def getVertices(self): 31 | return self.vertlist.keys() 32 | 33 | def __iter__(self): 34 | return iter(self.vertList.values()) 35 | -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Graph.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/Graph.pyc -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Graph.py~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/Graph.py~ -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Vertex.py: -------------------------------------------------------------------------------- 1 | 2 | class Vertex: 3 | def __init__(self,key): 4 | self.id = key 5 | self.connectedTo = {} 6 | 7 | def addNeighbor(self,nbr,weight=0): 8 | self.connectedTo[nbr] = weight 9 | 10 | def __str__(self): 11 | return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) 12 | 13 | def getConnections(self): 14 | return self.connectedTo.keys() 15 | 16 | def getId(self): 17 | return self.id 18 | 19 | def getWeight(self,nbr): 20 | return self.connectedTo[nbr] 21 | -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Vertex.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/Vertex.pyc -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/Vertex.py~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/Vertex.py~ -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/__pycache__/Graph.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/__pycache__/Graph.cpython-32.pyc -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/__pycache__/Vertex.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/chap07_graphs/01_adjacency_list/__pycache__/Vertex.cpython-32.pyc -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/testGraph.py: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | 3 | g = Graph() 4 | 5 | for i in range(6): 6 | g.addVertex(i) 7 | 8 | print(g.vertList) 9 | 10 | g.addEdge(0,1,5) 11 | g.addEdge(0,5,2) 12 | g.addEdge(1,2,4) 13 | g.addEdge(2,3,9) 14 | g.addEdge(3,4,7) 15 | g.addEdge(3,5,3) 16 | g.addEdge(4,0,1) 17 | g.addEdge(5,4,8) 18 | g.addEdge(5,2,1) 19 | 20 | for v in g: 21 | for w in v.getConnections(): 22 | print("( %s , %s )" % (v.getId(), w.getId())) 23 | -------------------------------------------------------------------------------- /chap07_graphs/01_adjacency_list/testGraph.py~: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | 3 | g = Graph() 4 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/Graph.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.vertList = {} 6 | self.numVertices = 0 7 | 8 | def addVertex(self,key): 9 | self.numVertices = self.numVertices + 1 10 | newVertex = Vertex(key) 11 | self.vertList[key] = newVertex 12 | return newVertex 13 | 14 | def getVertex(self,n): 15 | if n in self.vertList: 16 | return self.vertList[n] 17 | else: 18 | return None 19 | 20 | def __contains__(self,n): 21 | return n in self.vertList 22 | 23 | def addEdge(self,f,t,cost=0): 24 | if f not in self.vertList: 25 | nv = self.addVertex(f) 26 | if t not in self.vertList: 27 | nv = self.addVertex(t) 28 | self.vertList[f].addNeighbor(self.vertList[t], cost) 29 | 30 | def getVertices(self): 31 | return self.vertlist.keys() 32 | 33 | def __iter__(self): 34 | return iter(self.vertList.values()) 35 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/Queue.py: -------------------------------------------------------------------------------- 1 | 2 | class Queue: 3 | def __init__(self): 4 | self.items = [] 5 | 6 | def isEmpty(self): 7 | return self.items == [] 8 | 9 | def enqueue(self, item): 10 | self.items.insert(0,item) 11 | 12 | def dequeue(self): 13 | return self.items.pop() 14 | 15 | def size(self): 16 | return len(self.items) 17 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/Vertex.py: -------------------------------------------------------------------------------- 1 | 2 | class Vertex: 3 | def __init__(self,key): 4 | self.id = key 5 | self.connectedTo = {} 6 | self.color = 'white' 7 | self.dist = sys.maxsize 8 | self.pred = None 9 | self.disc = 0 10 | self.fin = 0 11 | 12 | def addNeighbor(self,nbr,weight=0): 13 | self.connectedTo[nbr] = weight 14 | 15 | def setColor(self,color): 16 | self.color = color 17 | 18 | def setDistance(self,d): 19 | self.dist = d 20 | 21 | def setPred(self,p): 22 | self.pred = p 23 | 24 | def setDiscovery(self,dtime): 25 | self.disc = dtime 26 | 27 | def setFinish(self,ftime): 28 | self.fin = ftime 29 | 30 | def getFinish(self): 31 | return self.fin 32 | 33 | def getDiscovery(self): 34 | return self.disc 35 | 36 | def getPred(self): 37 | return self.pred 38 | 39 | def getDistance(self): 40 | return self.dist 41 | 42 | def getColor(self): 43 | return self.color 44 | 45 | def getConnections(self): 46 | return self.connectedTo.keys() 47 | 48 | def getWeight(self,nbr): 49 | return self.connectedTo[nbr] 50 | 51 | def __str__(self): 52 | return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) 53 | 54 | def getId(self): 55 | return self.id 56 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/bfs.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | from Graph import Graph 3 | from Queue import Queue 4 | 5 | def bfs(g,start): 6 | start.setDistance(0) 7 | start.setPred(None) 8 | vertQueue = Queue() 9 | vertQueue.enqueue(start) 10 | while (vertQueue.start() > 0): 11 | currentVert = vertQueue.dequeue() 12 | for nbr in currentVert.getconnections(): 13 | if (nbr.getcolor() == 'white'): 14 | nbr.setColor('gray') 15 | nbr.setDistance(currentVert.getDistance() + 1) 16 | nbr.setPred(currentVert) 17 | vertQueue.enqueue(nbr) 18 | currentVert.setColor('black') 19 | 20 | 21 | def traverse(y): 22 | x = y 23 | while (x.getPred()): 24 | print(x.getId()) 25 | x = x.getPred() 26 | print(x.getId()) 27 | 28 | 29 | traverse(g.getVertex('sage')) 30 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/bfs.py~: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | from Graph import Graph 3 | from Queue import Queue 4 | 5 | def bfs(g,start): 6 | start.setDistance(0) 7 | start.setPred(None) 8 | vertQueue = Queue() 9 | vertQueue.enqueue(start) 10 | while (vertQueue.start() > 0): 11 | currentVert = vertQueue.dequeue() 12 | for nbr in currentVert.getconnections(): 13 | if (nbr.getcolor() == 'white'): 14 | nbr.setColor('gray') 15 | nbr.setDistance(currentVert.getDistance() + 1) 16 | nbr.setPred(currentVert) 17 | vertQueue.enqueue(nbr) 18 | currentVert.setColor('black') 19 | 20 | -------------------------------------------------------------------------------- /chap07_graphs/02_breadth_first_search/buildGraph.py: -------------------------------------------------------------------------------- 1 | 2 | from Graph import Graph 3 | 4 | def buildGraph(wordFile): 5 | d = [] 6 | g = graph() 7 | wfile = open(wordFile,'r') 8 | # create buckets of words that differ by one letter 9 | for line in wfile: 10 | word = line[:-1] 11 | for in in range(len(word)): 12 | bucket = word[:i] + '_' + word[i+1] 13 | if bucket in d: 14 | d[bucket].append(word) 15 | else: 16 | d[bucket] = [word] 17 | # add vertices and edges for words in the same bucket 18 | for bucket in d.keys(): 19 | for word1 in d[bucket]: 20 | for word2 in d[bucket]: 21 | if word1 != word2: 22 | g.addEdgs(word1,word2) 23 | return g -------------------------------------------------------------------------------- /chap07_graphs/03_depth_first_search/DFSGraph.py: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | class DFSGraph(Graph): 3 | def __init__(self): 4 | super().__init__() 5 | self.time = 0 6 | 7 | def dfs(self): 8 | for aVertex in self: 9 | aVertex.setColor('white') 10 | aVertex.setPred(-1) 11 | for aVertex in self: 12 | if aVertex.getColor() == 'white': 13 | self.dfsvisit(aVertex) 14 | 15 | def dfsvisit(self,startVertex): 16 | startVertex.setColor('gray') 17 | self.time += 1 18 | startVertex.setDiscovery(self.time) 19 | for nextVertex in startVertex.getConnections(): 20 | if nextVertex.getColor() == 'white': 21 | nextVertex.setPred(startVertex) 22 | self.dfsvisit(nextVertex) 23 | startVertex.setColor('black') 24 | self.time += 1 25 | startVertex.setFinish(self.time) 26 | -------------------------------------------------------------------------------- /chap07_graphs/03_depth_first_search/Graph.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.vertList = {} 6 | self.numVertices = 0 7 | 8 | def addVertex(self,key): 9 | self.numVertices = self.numVertices + 1 10 | newVertex = Vertex(key) 11 | self.vertList[key] = newVertex 12 | return newVertex 13 | 14 | def getVertex(self,n): 15 | if n in self.vertList: 16 | return self.vertList[n] 17 | else: 18 | return None 19 | 20 | def __contains__(self,n): 21 | return n in self.vertList 22 | 23 | def addEdge(self,f,t,cost=0): 24 | if f not in self.vertList: 25 | nv = self.addVertex(f) 26 | if t not in self.vertList: 27 | nv = self.addVertex(t) 28 | self.vertList[f].addNeighbor(self.vertList[t], cost) 29 | 30 | def getVertices(self): 31 | return self.vertlist.keys() 32 | 33 | def __iter__(self): 34 | return iter(self.vertList.values()) 35 | -------------------------------------------------------------------------------- /chap07_graphs/03_depth_first_search/Vertex.py: -------------------------------------------------------------------------------- 1 | 2 | class Vertex: 3 | def __init__(self,key): 4 | self.id = key 5 | self.connectedTo = {} 6 | self.color = 'white' 7 | self.dist = sys.maxsize 8 | self.pred = None 9 | self.disc = 0 10 | self.fin = 0 11 | 12 | def addNeighbor(self,nbr,weight=0): 13 | self.connectedTo[nbr] = weight 14 | 15 | def setColor(self,color): 16 | self.color = color 17 | 18 | def setDistance(self,d): 19 | self.dist = d 20 | 21 | def setPred(self,p): 22 | self.pred = p 23 | 24 | def setDiscovery(self,dtime): 25 | self.disc = dtime 26 | 27 | def setFinish(self,ftime): 28 | self.fin = ftime 29 | 30 | def getFinish(self): 31 | return self.fin 32 | 33 | def getDiscovery(self): 34 | return self.disc 35 | 36 | def getPred(self): 37 | return self.pred 38 | 39 | def getDistance(self): 40 | return self.dist 41 | 42 | def getColor(self): 43 | return self.color 44 | 45 | def getConnections(self): 46 | return self.connectedTo.keys() 47 | 48 | def getWeight(self,nbr): 49 | return self.connectedTo[nbr] 50 | 51 | def __str__(self): 52 | return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) 53 | 54 | def getId(self): 55 | return self.id 56 | -------------------------------------------------------------------------------- /chap07_graphs/03_depth_first_search/knightGraph.py: -------------------------------------------------------------------------------- 1 | from Graph inport Graph 2 | 3 | def knightGraph(bdSize): 4 | ktGraph = Graph() 5 | for row in range(bdSize): 6 | for col in range(bdSize): 7 | nodeId = posToNodeId(row,col,bdSize) 8 | newPositions = genLegalMoves(row,col,bdSize) 9 | for e in newPositions: 10 | nid = posToNodeId(e[0],e[1],bdSize) 11 | ktGraph.addEdge(nodeId,nid) 12 | return keGraph 13 | 14 | def genLegalMoves(x,y,bdSize): 15 | newMoves = [] 16 | moveOffsets = [(-1,-2),(-1,2),(-2,-1),(-2,1), 17 | ( 1,-2),( 1,2),( 2,-1),( 2,1)] 18 | for i in moveOffsets: 19 | newX = x + i[0] 20 | newY = y + i[1] 21 | if legalCoord(newX,bdSize) and legalCoord(newY,bdSize): 22 | newMoves.append((newX,newY)) 23 | return newMoves 24 | 25 | def legalCoord(x,bdSize): 26 | if x >= 0 and x < bdSize: 27 | return True 28 | else: 29 | return False 30 | 31 | 32 | -------------------------------------------------------------------------------- /chap07_graphs/03_depth_first_search/knightTour.py: -------------------------------------------------------------------------------- 1 | from Graph import Graph 2 | from Vertex import Vertex 3 | 4 | def knightTour(n,path,u,limit): 5 | u.setColor('gray') 6 | path.append(u) 7 | if n < limit: 8 | nbrList = list(u.getConnections()) 9 | i = 0 10 | done = False 11 | while i < len(nbrList) and not done: 12 | if nbrList[i].getColor() == 'white': 13 | done = knightTour(n+1, path, nbrList[i], limit) 14 | i = i + 1 15 | if not done: # prepare to backtrack 16 | path.pop() 17 | u.setColor('white') 18 | else: 19 | done = True 20 | return done 21 | 22 | 23 | def knightTour2(n,path,u,limit): 24 | u.setColor('gray') 25 | path.append(u) 26 | if n < limit: 27 | nbrList = orderByAvail(u) 28 | i = 0 29 | done = False 30 | while i < len(nbrList) and not done: 31 | if nbrList[i].getColor() == 'white': 32 | done = knightTour(n+1, path, nbrList[i], limit) 33 | i = i + 1 34 | if not done: # prepare to backtrack 35 | path.pop() 36 | u.setColor('white') 37 | else: 38 | done = True 39 | return done 40 | 41 | 42 | def orderByAvail(n): 43 | resList = [] 44 | for v in n.getConections(): 45 | if v.getColor() == 'white': 46 | c = 0 47 | for w in v.getConnections(): 48 | if w.getColor() == 'white': 49 | c = c + 1 50 | resList.append((c,v)) 51 | resList.sort(key=lambda x: x[0]) 52 | return [y[1] for y in resList] 53 | -------------------------------------------------------------------------------- /chap07_graphs/04_shortest_path/Graph.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | 3 | class Graph: 4 | def __init__(self): 5 | self.vertList = {} 6 | self.numVertices = 0 7 | 8 | def addVertex(self,key): 9 | self.numVertices = self.numVertices + 1 10 | newVertex = Vertex(key) 11 | self.vertList[key] = newVertex 12 | return newVertex 13 | 14 | def getVertex(self,n): 15 | if n in self.vertList: 16 | return self.vertList[n] 17 | else: 18 | return None 19 | 20 | def __contains__(self,n): 21 | return n in self.vertList 22 | 23 | def addEdge(self,f,t,cost=0): 24 | if f not in self.vertList: 25 | nv = self.addVertex(f) 26 | if t not in self.vertList: 27 | nv = self.addVertex(t) 28 | self.vertList[f].addNeighbor(self.vertList[t], cost) 29 | 30 | def getVertices(self): 31 | return self.vertlist.keys() 32 | 33 | def __iter__(self): 34 | return iter(self.vertList.values()) 35 | -------------------------------------------------------------------------------- /chap07_graphs/04_shortest_path/Vertex.py: -------------------------------------------------------------------------------- 1 | 2 | class Vertex: 3 | def __init__(self,key): 4 | self.id = key 5 | self.connectedTo = {} 6 | self.color = 'white' 7 | self.dist = sys.maxsize 8 | self.pred = None 9 | self.disc = 0 10 | self.fin = 0 11 | 12 | def addNeighbor(self,nbr,weight=0): 13 | self.connectedTo[nbr] = weight 14 | 15 | def setColor(self,color): 16 | self.color = color 17 | 18 | def setDistance(self,d): 19 | self.dist = d 20 | 21 | def setPred(self,p): 22 | self.pred = p 23 | 24 | def setDiscovery(self,dtime): 25 | self.disc = dtime 26 | 27 | def setFinish(self,ftime): 28 | self.fin = ftime 29 | 30 | def getFinish(self): 31 | return self.fin 32 | 33 | def getDiscovery(self): 34 | return self.disc 35 | 36 | def getPred(self): 37 | return self.pred 38 | 39 | def getDistance(self): 40 | return self.dist 41 | 42 | def getColor(self): 43 | return self.color 44 | 45 | def getConnections(self): 46 | return self.connectedTo.keys() 47 | 48 | def getWeight(self,nbr): 49 | return self.connectedTo[nbr] 50 | 51 | def __str__(self): 52 | return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo]) 53 | 54 | def getId(self): 55 | return self.id 56 | -------------------------------------------------------------------------------- /chap07_graphs/04_shortest_path/dijkstra.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | from Graph import Graph 3 | from PriorityQueue import PriorityQueue 4 | 5 | def dijkstra(aGraph,start): 6 | pq = PriorityQueue() 7 | start.setDistance(0) 8 | pq.buildHeap([(v.getDistance(),v) for v in aGraph]) 9 | while not pq.isEmpty(): 10 | currentVert = pq.delMin() 11 | for nextVert in currentVert.getConnections(): 12 | newDist = currentVert.getDistance() + currentVert.getWeight(nextVert) 13 | if newDist < nextVert.getDistance(): 14 | nextVert.getDistance( newDist ) 15 | nextVert.setPred(currentVert) 16 | pq.decreaseKey(nextVert,newdist) 17 | -------------------------------------------------------------------------------- /chap07_graphs/04_shortest_path/prim.py: -------------------------------------------------------------------------------- 1 | from Vertex import Vertex 2 | from Graph import Graph 3 | from PriorityQueue import PriorityQueue 4 | 5 | def prim(G,start): 6 | pr = PriorityQueue() 7 | for v in G: 8 | v.setDistance(sys.maxsize) 9 | v.setPred(None) 10 | start.setDistance(0) 11 | pq.buildHeap([(v.getDistance(),v) for v in G]) 12 | while not pq.isEmpty(): 13 | currentVert = pq.delMin() 14 | for nextVert in currentVert.getConnections(): 15 | newCost = currentVert.getWeight(nextVert) + currentVert.getDistance() 16 | if v in pq and newCost")) 12 | 13 | def getPinB(self): 14 | return int(input("Enter Pin B input for gate "+ \ 15 | self.getLabel()+"-->")) 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_12.py: -------------------------------------------------------------------------------- 1 | class UnaryGate(LogicGate): 2 | 3 | def __init__(self,n): 4 | super().__init__(n) 5 | 6 | self.pin = None 7 | 8 | def getPin(self): 9 | return int(input("Enter Pin input for gate "+ \ 10 | self.getLabel()+"-->")) 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_13.py: -------------------------------------------------------------------------------- 1 | class AndGate(BinaryGate): 2 | 3 | def __init__(self,n): 4 | super().__init__(n) 5 | 6 | def performGateLogic(self): 7 | 8 | a = self.getPinA() 9 | b = self.getPinB() 10 | if a==1 and b==1: 11 | return 1 12 | else: 13 | return 0 14 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_14.py: -------------------------------------------------------------------------------- 1 | class Connector: 2 | 3 | def __init__(self, fgate, tgate): 4 | self.fromgate = fgate 5 | self.togate = tgate 6 | 7 | tgate.setNextPin(self) 8 | 9 | def getFrom(self): 10 | return self.fromgate 11 | 12 | def getTo(self): 13 | return self.togate 14 | 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_15.py: -------------------------------------------------------------------------------- 1 | def setNextPin(self,source): 2 | if self.pinA == None: 3 | self.pinA = source 4 | else: 5 | if self.pinB == None: 6 | self.pinB = source 7 | else: 8 | raise RuntimeError("Error: NO EMPTY PINS") 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_16.py: -------------------------------------------------------------------------------- 1 | def getPinA(self): 2 | if self.pinA == None: 3 | return input("Enter Pin A input for gate "+ \ 4 | self.getName()+"-->") 5 | else: 6 | return self.pinA.getFrom().getOutput() 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_2.py: -------------------------------------------------------------------------------- 1 | class Fraction: 2 | 3 | def __init__(self,top,bottom): 4 | 5 | self.num = top 6 | self.den = bottom 7 | 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_3.py: -------------------------------------------------------------------------------- 1 | def show(self): 2 | print(self.num,"/",self.den) 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_4.py: -------------------------------------------------------------------------------- 1 | def __str__(self): 2 | return str(self.num)+"/"+str(self.den) 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_5.py: -------------------------------------------------------------------------------- 1 | def __add__(self,otherfraction): 2 | 3 | newnum = self.num*otherfraction.den + \ 4 | self.den*otherfraction.num 5 | newden = self.den * otherfraction.den 6 | 7 | return Fraction(newnum,newden) 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_6.py: -------------------------------------------------------------------------------- 1 | def gcd(m,n): 2 | while m%n != 0: 3 | oldm = m 4 | oldn = n 5 | 6 | m = oldn 7 | n = oldm%oldn 8 | return n 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_7.py: -------------------------------------------------------------------------------- 1 | def __add__(self,otherfraction): 2 | newnum = self.num*otherfraction.den + \ 3 | self.den*otherfraction.num 4 | newden = self.den * otherfraction.den 5 | common = gcd(newnum,newden) 6 | return Fraction(newnum//common,newden//common) 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_8.py: -------------------------------------------------------------------------------- 1 | def __eq__(self, other): 2 | firstnum = self.num * other.den 3 | secondnum = other.num * self.den 4 | 5 | return firstnum == secondnum 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_1_9.py: -------------------------------------------------------------------------------- 1 | class Fraction: 2 | def __init__(self,top,bottom): 3 | self.num = top 4 | self.den = bottom 5 | 6 | def __str__(self): 7 | return str(self.num)+"/"+str(self.den) 8 | 9 | def show(self): 10 | print(self.num,"/",self.den) 11 | 12 | def __add__(self,otherfraction): 13 | newnum = self.num*otherfraction.den + \ 14 | self.den*otherfraction.num 15 | newden = self.den * otherfraction.den 16 | common = gcd(newnum,newden) 17 | return Fraction(newnum//common,newden//common) 18 | 19 | def __eq__(self, other): 20 | firstnum = self.num * other.den 21 | secondnum = other.num * self.den 22 | 23 | return firstnum == secondnum 24 | 25 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_1.py: -------------------------------------------------------------------------------- 1 | def sumOfN(n): 2 | theSum = 0 3 | for i in range(1,n+1): 4 | theSum = theSum + i 5 | 6 | return theSum 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_10.py: -------------------------------------------------------------------------------- 1 | 2 | popzero = timeit.Timer("x.pop(0)", 3 | "from __main__ import x") 4 | popend = timeit.Timer("x.pop()", 5 | "from __main__ import x") 6 | 7 | x = list(range(2000000)) 8 | popzero.timeit(number=1000) 9 | 4.8213560581207275 10 | 11 | x = list(range(2000000)) 12 | popend.timeit(number=1000) 13 | 0.0003161430358886719 14 | 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_11.py: -------------------------------------------------------------------------------- 1 | List Sizes},label=lst:poplists,index={pop performance},float=htb] 2 | 3 | popzero = Timer("x.pop(0)", 4 | "from __main__ import x") 5 | popend = Timer("x.pop()", 6 | "from __main__ import x") 7 | print("pop(0) pop()") 8 | for i in range(1000000,100000001,1000000): 9 | x = list(range(i)) 10 | pt = popend.timeit(number=1000) 11 | x = list(range(i)) 12 | pz = popzero.timeit(number=1000) 13 | print("%15.5f, %15.5f" %(pz,pt)) 14 | 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_12.py: -------------------------------------------------------------------------------- 1 | and Dictionary},label=lst:listvdict,index={dictionary performance},float=htb] 2 | import timeit 3 | import random 4 | 5 | for i in range(10000,1000001,20000): 6 | t = timeit.Timer("random.randrange(%d) in x"%i, 7 | "from __main__ import random,x") 8 | x = list(range(i)) 9 | lst_time = t.timeit(number=1000) 10 | x = {j:None for j in range(i)} 11 | d_time = t.timeit(number=1000) 12 | print("%d,%10.3f,%10.3f" % (i, lst_time, d_time)) 13 | 14 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_2.py: -------------------------------------------------------------------------------- 1 | def foo(tom): 2 | fred = 0 3 | for bill in range(1,tom+1): 4 | barney = bill 5 | fred = fred + barney 6 | 7 | return fred 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_3.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def sumOfN2(n): 4 | start = time.time() 5 | 6 | theSum = 0 7 | for i in range(1,n+1): 8 | theSum = theSum + i 9 | 10 | end = time.time() 11 | 12 | return theSum,end-start 13 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_4.py: -------------------------------------------------------------------------------- 1 | def sumOfN3(n): 2 | return (n*(n+1))/2 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_5.py: -------------------------------------------------------------------------------- 1 | a=5 2 | b=6 3 | c=10 4 | for i in range(n): 5 | for j in range(n): 6 | x = i * i 7 | y = j * j 8 | z = i * j 9 | for k in range(n): 10 | w = a*k + 45 11 | v = b*b 12 | d = 33 13 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_6.py: -------------------------------------------------------------------------------- 1 | def anagramSolution1(s1,s2): 2 | alist = list(s2) 3 | 4 | pos1 = 0 5 | stillOK = True 6 | 7 | while pos1 < len(s1) and stillOK: 8 | pos2 = 0 9 | found = False 10 | while pos2 < len(alist) and not found: 11 | if s1[pos1] == alist[pos2]: 12 | found = True 13 | else: 14 | pos2 = pos2 + 1 15 | 16 | if found: 17 | alist[pos2] = None 18 | else: 19 | stillOK = False 20 | 21 | pos1 = pos1 + 1 22 | 23 | return stillOK 24 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_7.py: -------------------------------------------------------------------------------- 1 | def anagramSolution2(s1,s2): 2 | alist1 = list(s1) 3 | alist2 = list(s2) 4 | 5 | alist1.sort() 6 | alist2.sort() 7 | 8 | pos = 0 9 | matches = True 10 | 11 | while pos < len(s1) and matches: 12 | if alist1[pos]==alist2[pos]: 13 | pos = pos + 1 14 | else: 15 | matches = False 16 | 17 | return matches 18 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_8.py: -------------------------------------------------------------------------------- 1 | def anagramSolution4(s1,s2): 2 | c1 = [0]*26 3 | c2 = [0]*26 4 | 5 | for i in range(len(s1)): 6 | pos = ord(s1[i])-ord('a') 7 | c1[pos] = c1[pos] + 1 8 | 9 | for i in range(len(s2)): 10 | pos = ord(s2[i])-ord('a') 11 | c2[pos] = c2[pos] + 1 12 | 13 | j = 0 14 | stillOK = True 15 | while j<26 and stillOK: 16 | if c1[j]==c2[j]: 17 | j = j + 1 18 | else: 19 | stillOK = False 20 | 21 | return stillOK 22 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_2_9.py: -------------------------------------------------------------------------------- 1 | def test1(): 2 | l = [] 3 | for i in range(1000): 4 | l = l + [i] 5 | 6 | def test2(): 7 | l = [] 8 | for i in range(1000): 9 | l.append(i) 10 | 11 | def test3(): 12 | l = [i for i in range(1000)] 13 | 14 | def test4(): 15 | l = list(range(1000)) 16 | 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_1.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | return self.items == [] 7 | 8 | def push(self, item): 9 | self.items.append(item) 10 | 11 | def pop(self): 12 | return self.items.pop() 13 | 14 | def peek(self): 15 | return self.items[len(self.items)-1] 16 | 17 | def size(self): 18 | return len(self.items) 19 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_10.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Queue 2 | def hotPotato(namelist, num): 3 | simqueue = Queue() 4 | for name in namelist: 5 | simqueue.enqueue(name) 6 | 7 | while simqueue.size() > 1: 8 | for i in range(num): 9 | simqueue.enqueue(simqueue.dequeue()) 10 | 11 | simqueue.dequeue() 12 | 13 | return simqueue.dequeue() 14 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_11.py: -------------------------------------------------------------------------------- 1 | class Printer: 2 | def __init__(self, ppm): 3 | self.pagerate = ppm 4 | self.currentTask = None 5 | self.timeRemaining = 0 6 | 7 | def tick(self): 8 | if self.currentTask != None: 9 | self.timeRemaining = self.timeRemaining - 1 10 | if self.timeRemaining <= 0: 11 | self.currentTask = None 12 | 13 | def busy(self): 14 | if self.currentTask != None: 15 | return True 16 | else: 17 | return False 18 | 19 | def startNext(self,newtask): 20 | self.currentTask = newtask 21 | self.timeRemaining = newtask.getPages() \ 22 | * 60/self.pagerate 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_12.py: -------------------------------------------------------------------------------- 1 | import random 2 | class Task: 3 | def __init__(self,time): 4 | self.timestamp = time 5 | self.pages = random.randrange(1,21) 6 | 7 | def getStamp(self): 8 | return self.timestamp 9 | 10 | def getPages(self): 11 | return self.pages 12 | 13 | def waitTime(self, currenttime): 14 | return currenttime - self.timestamp 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_13.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Queue 2 | 3 | import random 4 | 5 | def simulation(numSeconds, pagesPerMinute): 6 | 7 | labprinter = Printer(pagesPerMinute) 8 | printQueue = Queue() 9 | waitingtimes = [] 10 | 11 | for currentSecond in range(numSeconds): 12 | 13 | if newPrintTask(): 14 | task = Task(currentSecond) 15 | printQueue.enqueue(task) 16 | 17 | if (not labprinter.busy()) and \ 18 | (not printQueue.isEmpty()): 19 | nexttask = printQueue.dequeue() 20 | waitingtimes.append( \ 21 | nexttask.waitTime(currentSecond)) 22 | labprinter.startNext(nexttask) 23 | 24 | labprinter.tick() 25 | 26 | averageWait=sum(waitingtimes)/len(waitingtimes) 27 | print("Average Wait %6.2f secs %3d tasks remaining."\ 28 | %(averageWait,printQueue.size())) 29 | 30 | 31 | 32 | def newPrintTask(): 33 | num = random.randrange(1,181) 34 | if num == 180: 35 | return True 36 | else: 37 | return False 38 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_14.py: -------------------------------------------------------------------------------- 1 | class Deque: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | return self.items == [] 7 | 8 | def addFront(self, item): 9 | self.items.append(item) 10 | 11 | def addRear(self, item): 12 | self.items.insert(0,item) 13 | 14 | def removeFront(self): 15 | return self.items.pop() 16 | 17 | def removeRear(self): 18 | return self.items.pop(0) 19 | 20 | def size(self): 21 | return len(self.items) 22 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_15.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Deque 2 | def palchecker(aString): 3 | chardeque = Deque() 4 | 5 | for ch in aString: 6 | chardeque.addRear(ch) 7 | 8 | stillEqual = True 9 | 10 | while chardeque.size() > 1 and stillEqual: 11 | first = chardeque.removeFront() 12 | last = chardeque.removeRear() 13 | if first != last: 14 | stillEqual = False 15 | 16 | return stillEqual 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_16.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,initdata): 3 | self.data = initdata 4 | self.next = None 5 | 6 | def getData(self): 7 | return self.data 8 | 9 | def getNext(self): 10 | return self.next 11 | 12 | def setData(self,newdata): 13 | self.data = newdata 14 | 15 | def setNext(self,newnext): 16 | self.next = newnext 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_17.py: -------------------------------------------------------------------------------- 1 | class UnorderedList: 2 | def __init__(self): 3 | self.head = None 4 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_18.py: -------------------------------------------------------------------------------- 1 | def isEmpty(self): 2 | return self.head == None 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_19.py: -------------------------------------------------------------------------------- 1 | def add(self,item): 2 | temp = Node(item) 3 | temp.setNext(self.head) 4 | self.head = temp 5 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_2.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | return self.items == [] 7 | 8 | def push(self, item): 9 | self.items.insert(0,item) 10 | 11 | def pop(self): 12 | return self.items.pop(0) 13 | 14 | def peek(self): 15 | return self.items[0] 16 | 17 | def size(self): 18 | return len(self.items) 19 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_20.py: -------------------------------------------------------------------------------- 1 | def length(self): 2 | current = self.head 3 | count = 0 4 | while current != None: 5 | count = count + 1 6 | current = current.getNext() 7 | 8 | return count 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_21.py: -------------------------------------------------------------------------------- 1 | def search(self,item): 2 | current = self.head 3 | found = False 4 | while current != None and not found: 5 | if current.getData() == item: 6 | found = True 7 | else: 8 | current = current.getNext() 9 | 10 | return found 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_22.py: -------------------------------------------------------------------------------- 1 | def remove(self,item): 2 | current = self.head 3 | previous = None 4 | found = False 5 | while not found: 6 | if current.getData() == item: 7 | found = True 8 | else: 9 | previous = current 10 | current = current.getNext() 11 | 12 | if previous == None: 13 | self.head = current.getNext() 14 | else: 15 | previous.setNext(current.getNext()) 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_23.py: -------------------------------------------------------------------------------- 1 | class OrderedList: 2 | def __init__(self): 3 | self.head = None 4 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_24.py: -------------------------------------------------------------------------------- 1 | def search(self,item): 2 | current = self.head 3 | found = False 4 | stop = False 5 | while current != None and not found and not stop: 6 | if current.getData() == item: 7 | found = True 8 | else: 9 | if current.getData() > item: 10 | stop = True 11 | else: 12 | current = current.getNext() 13 | 14 | return found 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_25.py: -------------------------------------------------------------------------------- 1 | def add(self,item): 2 | current = self.head 3 | previous = None 4 | stop = False 5 | while current != None and not stop: 6 | if current.getData() > item: 7 | stop = True 8 | else: 9 | previous = current 10 | current = current.getNext() 11 | 12 | temp = Node(item) 13 | if previous == None: 14 | temp.setNext(self.head) 15 | self.head = temp 16 | else: 17 | temp.setNext(current) 18 | previous.setNext(temp) 19 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_3.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | 3 | def parChecker(symbolString): 4 | s = Stack() 5 | balanced = True 6 | index = 0 7 | while index < len(symbolString) and balanced: 8 | symbol = symbolString[index] 9 | if symbol == "(": 10 | s.push(symbol) 11 | else: 12 | if s.isEmpty(): 13 | balanced = False 14 | else: 15 | s.pop() 16 | 17 | index = index + 1 18 | 19 | if balanced and s.isEmpty(): 20 | return True 21 | else: 22 | return False 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_4.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | def parChecker(symbolString): 3 | s = Stack() 4 | 5 | balanced = True 6 | index = 0 7 | 8 | while index < len(symbolString) and balanced: 9 | symbol = symbolString[index] 10 | if symbol in "([{": 11 | s.push(symbol) 12 | else: 13 | if s.isEmpty(): 14 | balanced = False 15 | else: 16 | top = s.pop() 17 | if not matches(top,symbol): 18 | balanced = False 19 | 20 | index = index + 1 21 | 22 | if balanced and s.isEmpty(): 23 | return True 24 | else: 25 | return False 26 | 27 | def matches(open,close): 28 | opens = "([{" 29 | closers = ")]}" 30 | 31 | return opens.index(open) == closers.index(close) 32 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_5.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | def divideBy2(decNumber): 3 | remstack = Stack() 4 | 5 | while decNumber > 0: 6 | rem = decNumber % 2 7 | remstack.push(rem) 8 | decNumber = decNumber // 2 9 | 10 | binString = "" 11 | while not remstack.isEmpty(): 12 | binString = binString + str(remstack.pop()) 13 | 14 | return binString 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_6.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | def baseConverter(decNumber,base): 3 | digits = "0123456789ABCDEF" 4 | 5 | remstack = Stack() 6 | 7 | while decNumber > 0: 8 | rem = decNumber % base 9 | remstack.push(rem) 10 | decNumber = decNumber // base 11 | 12 | newString = "" 13 | while not remstack.isEmpty(): 14 | newString = newString + digits[remstack.pop()] 15 | 16 | return newString 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_7.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | import string 3 | 4 | def infixToPostfix(infixexpr): 5 | prec = {} 6 | prec["*"] = 3 7 | prec["/"] = 3 8 | prec["+"] = 2 9 | prec["-"] = 2 10 | prec["("] = 1 11 | 12 | opStack = Stack() 13 | postfixList = [] 14 | 15 | tokenList = infixexpr.split() 16 | 17 | for token in tokenList: 18 | if token in string.ascii_uppercase: 19 | postfixList.append(token) 20 | elif token == '(': 21 | opStack.push(token) 22 | elif token == ')': 23 | topToken = opStack.pop() 24 | while topToken != '(': 25 | postfixList.append(topToken) 26 | topToken = opStack.pop() 27 | else: 28 | while (not opStack.isEmpty()) and \ 29 | (prec[opStack.peek()] >= prec[token]): 30 | postfixList.append(opStack.pop()) 31 | opStack.push(token) 32 | 33 | while not opStack.isEmpty(): 34 | postfixList.append(opStack.pop()) 35 | 36 | return " ".join(postfixList) 37 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_8.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | def postfixEval(postfixExpr): 3 | operandStack = Stack() 4 | 5 | tokenList = postfixExpr.split() 6 | 7 | for token in tokenList: 8 | if token in "0123456789": 9 | operandStack.push(int(token)) 10 | else: 11 | operand2 = operandStack.pop() 12 | operand1 = operandStack.pop() 13 | result = doMath(token,operand1,operand2) 14 | operandStack.push(result) 15 | 16 | return operandStack.pop() 17 | 18 | def doMath(op, op1, op2): 19 | if op == "*": 20 | return op1 * op2 21 | elif op == "/": 22 | return op1 / op2 23 | elif op == "+": 24 | return op1 + op2 25 | else: 26 | return op1 - op2 27 | 28 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_3_9.py: -------------------------------------------------------------------------------- 1 | class Queue: 2 | def __init__(self): 3 | self.items = [] 4 | 5 | def isEmpty(self): 6 | return self.items == [] 7 | 8 | def enqueue(self, item): 9 | self.items.insert(0,item) 10 | 11 | def dequeue(self): 12 | return self.items.pop() 13 | 14 | def size(self): 15 | return len(self.items) 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_1.py: -------------------------------------------------------------------------------- 1 | def listsum(numList): 2 | theSum = 0 3 | for i in numList: 4 | theSum = theSum + i 5 | return theSum 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_10.py: -------------------------------------------------------------------------------- 1 | def searchFrom(maze, startRow, startColumn): 2 | maze.updatePosition(startRow, startColumn) 3 | # Check for base cases: 4 | # 1. We have run into an obstacle, return false 5 | if maze[startRow][startColumn] == OBSTACLE : 6 | return False 7 | # 2. We have found a square that has already been explored 8 | if maze[startRow][startColumn] == TRIED: 9 | return False 10 | # 3. Success, an outside edge not occupied by an obstacle 11 | if maze.isExit(startRow,startColumn): 12 | maze.updatePosition(startRow, startColumn, PART_OF_PATH) 13 | return True 14 | maze.updatePosition(startRow, startColumn, TRIED) 15 | 16 | # Otherwise, use logical short circuiting to try each 17 | # direction in turn (if needed) 18 | found = searchFrom(maze, startRow-1, startColumn) or \ 19 | searchFrom(maze, startRow+1, startColumn) or \ 20 | searchFrom(maze, startRow, startColumn-1) or \ 21 | searchFrom(maze, startRow, startColumn+1) 22 | if found: 23 | maze.updatePosition(startRow, startColumn, PART_OF_PATH) 24 | else: 25 | maze.updatePosition(startRow, startColumn, DEAD_END) 26 | return found 27 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_11.py: -------------------------------------------------------------------------------- 1 | class Maze: 2 | def __init__(self,mazeFileName): 3 | rowsInMaze = 0 4 | columnsInMaze = 0 5 | self.mazelist = [] 6 | mazeFile = open(mazeFileName,'r') 7 | rowsInMaze = 0 8 | for line in mazeFile: 9 | rowList = [] 10 | col = 0 11 | for ch in line[:-1]: 12 | rowList.append(ch) 13 | if ch == 'S': 14 | self.startRow = rowsInMaze 15 | self.startCol = col 16 | col = col + 1 17 | rowsInMaze = rowsInMaze + 1 18 | self.mazelist.append(rowList) 19 | columnsInMaze = len(rowList) 20 | 21 | self.rowsInMaze = rowsInMaze 22 | self.columnsInMaze = columnsInMaze 23 | self.xTranslate = -columnsInMaze/2 24 | self.yTranslate = rowsInMaze/2 25 | self.t = Turtle(shape='turtle') 26 | setup(width=600,height=600) 27 | setworldcoordinates(-(columnsInMaze-1)/2-.5, 28 | -(rowsInMaze-1)/2-.5, 29 | (columnsInMaze-1)/2+.5, 30 | (rowsInMaze-1)/2+.5) 31 | 32 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_12.py: -------------------------------------------------------------------------------- 1 | def drawMaze(self): 2 | for y in range(self.rowsInMaze): 3 | for x in range(self.columnsInMaze): 4 | if self.mazelist[y][x] == OBSTACLE: 5 | self.drawCenteredBox(x+self.xTranslate, 6 | -y+self.yTranslate, 7 | 'tan') 8 | self.t.color('black','blue') 9 | 10 | def drawCenteredBox(self,x,y,color): 11 | tracer(0) 12 | self.t.up() 13 | self.t.goto(x-.5,y-.5) 14 | self.t.color('black',color) 15 | self.t.setheading(90) 16 | self.t.down() 17 | self.t.begin_fill() 18 | for i in range(4): 19 | self.t.forward(1) 20 | self.t.right(90) 21 | self.t.end_fill() 22 | update() 23 | tracer(1) 24 | 25 | def moveTurtle(self,x,y): 26 | self.t.up() 27 | self.t.setheading(self.t.towards(x+self.xTranslate, 28 | -y+self.yTranslate)) 29 | self.t.goto(x+self.xTranslate,-y+self.yTranslate) 30 | 31 | def dropBreadcrumb(self,color): 32 | self.t.dot(color) 33 | 34 | def updatePosition(self,row,col,val=None): 35 | if val: 36 | self.mazelist[row][col] = val 37 | self.moveTurtle(col,row) 38 | 39 | if val == PART_OF_PATH: 40 | color = 'green' 41 | elif val == OBSTACLE: 42 | color = 'red' 43 | elif val == TRIED: 44 | color = 'black' 45 | elif val == DEAD_END: 46 | color = 'red' 47 | else: 48 | color = None 49 | 50 | if color: 51 | self.dropBreadcrumb(color) 52 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_13.py: -------------------------------------------------------------------------------- 1 | def isExit(self,row,col): 2 | return (row == 0 or 3 | row == self.rowsInMaze-1 or 4 | col == 0 or 5 | col == self.columnsInMaze-1 ) 6 | 7 | def __getitem__(self,idx): 8 | return self.mazelist[idx] 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_14.py: -------------------------------------------------------------------------------- 1 | def recMC(coinValueList,change): 2 | minCoins = change 3 | if change in coinValueList: return 1 4 | else: 5 | for i in [c for c in coinValueList if c <= change]: numCoins = 1 + recMC(coinValueList,change-i) if numCoins < minCoins: 6 | minCoins = numCoins 7 | return minCoins 8 | 9 | recMC([1,5,10,25],63) 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_15.py: -------------------------------------------------------------------------------- 1 | def recDC(coinValueList,change,knownResults): 2 | minCoins = change 3 | if change in coinValueList: 4 | knownResults[change] = 1 5 | return 1 6 | elif knownResults[change] > 0: return knownResults[change] 7 | else: 8 | for i in [c for c in coinValueList if c <= change]: 9 | numCoins = 1 + recDC(coinValueList, change-i, 10 | knownResults) 11 | if numCoins < minCoins: 12 | minCoins = numCoins 13 | knownResults[change] = minCoins 14 | return minCoins 15 | 16 | recDC([1,5,10,25],63,[0]*63) 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_16.py: -------------------------------------------------------------------------------- 1 | def dpMakeChange(coinValueList,change,minCoins): 2 | for cents in range(change+1): 3 | coinCount = cents 4 | for j in [c for c in coinValueList if c <= cents]: if minCoins[cents-j] + 1 < coinCount: 5 | coinCount = minCoins[cents-j]+1 6 | minCoins[cents] = coinCount 7 | return minCoins[change] 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_17.py: -------------------------------------------------------------------------------- 1 | def dpMakeChange(coinValueList,change,minCoins,coinsUsed): 2 | for cents in range(change+1): 3 | coinCount = cents 4 | newCoin = 1 5 | for j in [c for c in coinValueList if c <= cents]: 6 | if minCoins[cents-j] + 1 < coinCount: 7 | coinCount = minCoins[cents-j]+1 8 | newCoin = j 9 | minCoins[cents] = coinCount 10 | coinsUsed[cents] = newCoin 11 | return minCoins[change] 12 | 13 | def printCoins(coinsUsed,change): 14 | coin = change 15 | while coin > 0: 16 | thisCoin = coinsUsed[coin] 17 | print(thisCoin) 18 | coin = coin - thisCoin 19 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_2.py: -------------------------------------------------------------------------------- 1 | def listsum(numList): 2 | if len(numList) == 1: return numList[0] 3 | else: 4 | return numList[0] + listsum(numList[1:]) -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_3.py: -------------------------------------------------------------------------------- 1 | 2 | def toStr(n,base): 3 | convertString = "0123456789ABCDEF" 4 | if n < base: return convertString[n] 5 | else: 6 | return toStr(n//base,base) + convertString[n%base] -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_4.py: -------------------------------------------------------------------------------- 1 | rStack = Stack() 2 | 3 | def toStr(n,base): 4 | convertString = "0123456789ABCDEF" 5 | if n < base: 6 | rStack.push(convertString[n]) 7 | else: 8 | rStack.push(convertString[n % base]) 9 | toStr(n // base, base) 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_5.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | 3 | myTurtle = Turtle() 4 | myWin = myTurtle.getscreen() 5 | 6 | def drawSpiral(myTurtle, lineLen): 7 | if len > 0: 8 | myTurtle.forward(lineLen) 9 | myTurtle.right(90) 10 | drawSpiral(myTurtle,lineLen-5) 11 | 12 | drawSpiral(myTurtle,100) 13 | myWin.exitonclick() 14 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_6.py: -------------------------------------------------------------------------------- 1 | def tree(branchLen,t): 2 | if branchLen > 5: 3 | t.forward(branchLen) 4 | t.right(20) 5 | tree(branchLen-15,t) 6 | t.left(40) 7 | tree(branchLen-10,t) 8 | t.right(20) 9 | t.backward(branchLen) 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_7.py: -------------------------------------------------------------------------------- 1 | from turtle import * 2 | 3 | def drawTriangle(points,color,myTurtle): 4 | myTurtle.fillcolor(color) 5 | myTurtle.up() 6 | myTurtle.goto(points[0]) 7 | myTurtle.down() 8 | myTurtle.begin_fill() 9 | myTurtle.goto(points[1]) 10 | myTurtle.goto(points[2]) 11 | myTurtle.goto(points[0]) 12 | myTurtle.end_fill() 13 | 14 | def getMid(p1,p2): 15 | return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) 16 | 17 | def sierpinski(points,degree,myTurtle): 18 | colormap = ['blue','red','green','white','yellow', 19 | 'violet','orange'] 20 | drawTriangle(points,colormap[degree],myTurtle) 21 | if degree > 0: 22 | sierpinski([points[0], 23 | getMid(points[0], points[1]), 24 | getMid(points[0], points[2])], 25 | degree-1, myTurtle) 26 | sierpinski([points[1], 27 | getMid(points[0], points[1]), 28 | getMid(points[1], points[2])], 29 | degree-1, myTurtle) 30 | sierpinski([points[2], 31 | getMid(points[2], points[1]), 32 | getMid(points[0], points[2])], 33 | degree-1, myTurtle) 34 | 35 | myTurtle = Turtle() 36 | myWin = myTurtle.getscreen() 37 | myPoints = [(-500,-250),(0,500),(500,-250)] 38 | sierpinski(myPoints,5,myTurtle) 39 | myWin.exitonclick() 40 | 41 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_8.py: -------------------------------------------------------------------------------- 1 | def moveTower(height,fromPole, toPole, withPole): 2 | if height >= 1: 3 | moveTower(height-1,fromPole,withPole,toPole) moveDisk(fromPole,toPole) 4 | moveTower(height-1,withPole,toPole,fromPole) 5 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_4_9.py: -------------------------------------------------------------------------------- 1 | def moveDisk(fp,tp): 2 | print("moving disk from %d to %d\n" % (fp,tp)) 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_1.py: -------------------------------------------------------------------------------- 1 | def sequentialSearch(alist, item): 2 | pos = 0 3 | found = False 4 | 5 | while pos < len(alist) and not found: 6 | if alist[pos] == item: 7 | found = True 8 | else: 9 | pos = pos+1 10 | 11 | return found 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_10.py: -------------------------------------------------------------------------------- 1 | def shortBubbleSort(alist): 2 | exchanges = True 3 | passnum = len(alist)-1 4 | while passnum > 0 and exchanges: 5 | exchanges = False 6 | for i in range(passnum): 7 | if alist[i]>alist[i+1]: 8 | exchanges = True 9 | temp = alist[i] 10 | alist[i] = alist[i+1] 11 | alist[i+1] = temp 12 | passnum = passnum-1 13 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_11.py: -------------------------------------------------------------------------------- 1 | def selectionSort(alist): 2 | for fillslot in range(len(alist)-1,0,-1): 3 | positionOfMax=0 4 | for location in range(1,fillslot+1): 5 | if alist[location]>alist[positionOfMax]: 6 | positionOfMax = location 7 | 8 | temp = alist[fillslot] 9 | alist[fillslot] = alist[positionOfMax] 10 | alist[positionOfMax] = temp 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_12.py: -------------------------------------------------------------------------------- 1 | def insertionSort(alist): 2 | for index in range(1,len(alist)): 3 | 4 | currentvalue = alist[index] 5 | position = index 6 | 7 | while position>0 and alist[position-1]>currentvalue: 8 | alist[position]=alist[position-1] 9 | position = position-1 10 | 11 | alist[position]=currentvalue 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_13.py: -------------------------------------------------------------------------------- 1 | def shellSort(alist): 2 | sublistcount = len(alist)//2 3 | while sublistcount > 0: 4 | 5 | for startposition in range(sublistcount): 6 | gapInsertionSort(alist,startposition,sublistcount) 7 | 8 | print("After increments of size",sublistcount, 9 | "The list is",alist) 10 | 11 | sublistcount = sublistcount // 2 12 | 13 | def gapInsertionSort(alist,start,gap): 14 | for i in range(start+gap,len(alist),gap): 15 | 16 | currentvalue = alist[i] 17 | position = i 18 | 19 | while position>=gap and \ 20 | alist[position-gap]>currentvalue: 21 | alist[position]=alist[position-gap] 22 | position = position-gap 23 | 24 | alist[position]=currentvalue 25 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_14.py: -------------------------------------------------------------------------------- 1 | def mergeSort(alist): 2 | print("Splitting ",alist) 3 | if len(alist)>1: 4 | mid = len(alist)//2 5 | lefthalf = alist[:mid] 6 | righthalf = alist[mid:] 7 | 8 | mergeSort(lefthalf) 9 | mergeSort(righthalf) 10 | 11 | i=0 12 | j=0 13 | k=0 14 | while i= pivotvalue and \ 27 | rightmark >= leftmark: 28 | rightmark = rightmark -1 29 | 30 | if rightmark < leftmark: 31 | done = True 32 | else: 33 | temp = alist[leftmark] 34 | alist[leftmark] = alist[rightmark] 35 | alist[rightmark] = temp 36 | 37 | temp = alist[first] 38 | alist[first] = alist[rightmark] 39 | alist[rightmark] = temp 40 | 41 | 42 | return rightmark 43 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_2.py: -------------------------------------------------------------------------------- 1 | def orderedSequentialSearch(alist, item): 2 | pos = 0 3 | found = False 4 | stop = False 5 | while pos < len(alist) and not found and not stop: 6 | if alist[pos] == item: 7 | found = True 8 | else: 9 | if alist[pos] > item: 10 | stop = True 11 | else: 12 | pos = pos+1 13 | 14 | return found 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_3.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist, item): 2 | first = 0 3 | last = len(alist)-1 4 | found = False 5 | 6 | while first<=last and not found: 7 | midpoint = (first + last)//2 8 | if alist[midpoint] == item: 9 | found = True 10 | else: 11 | if item < alist[midpoint]: 12 | last = midpoint-1 13 | else: 14 | first = midpoint+1 15 | 16 | return found 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_5_4.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist, item): 2 | if len(alist) == 0: 3 | return False 4 | else: 5 | midpoint = len(alist)//2 6 | if alist[midpoint]==item: 7 | return True 8 | else: 9 | if itemalist[i+1]: 5 | temp = alist[i] 6 | alist[i] = alist[i+1] 7 | alist[i+1] = temp 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_1.py: -------------------------------------------------------------------------------- 1 | def BinaryTree(r): 2 | return [r, [], []] 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_10.py: -------------------------------------------------------------------------------- 1 | def evaluate(parseTree): 2 | opers = {'+':operator.add, '-':operator.sub, 3 | '*':operator.mul, '/':operator.truediv} 4 | leftC = parseTree.getLeftChild() 5 | rightC = parseTree.getRightChild() 6 | 7 | if leftC and rightC: fn = opers[parseTree.getRootVal()] 8 | return fn(evaluate(leftC),evaluate(rightC)) else: 9 | return parseTree.getRootVal() 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_11.py: -------------------------------------------------------------------------------- 1 | def preorder(tree): 2 | if tree: 3 | print(tree.getRootVal()) 4 | preorder(tree.getLeftChild()) 5 | preorder(tree.getRightChild()) 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_12.py: -------------------------------------------------------------------------------- 1 | def preorder(self): 2 | print(self.key) 3 | if self.leftChild: 4 | self.left.preorder() 5 | if self.rightChild: 6 | self.right.preorder() 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_13.py: -------------------------------------------------------------------------------- 1 | def postorder(tree): 2 | if tree != None: 3 | postorder(tree.getLeftChild()) 4 | postorder(tree.getRightChild()) 5 | print(tree.getRootVal()) 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_14.py: -------------------------------------------------------------------------------- 1 | def postordereval(tree): 2 | opers = {'+':operator.add, '-':operator.sub, 3 | '*':operator.mul, '/':operator.truediv} 4 | res1 = None 5 | res2 = None 6 | if tree: 7 | res1 = postordereval(tree.getLeftChild()) res2 = postordereval(tree.getRightChild()) if res1 and res2: 8 | return opers[tree.getRootVal()](res1,res2) else: 9 | return tree.getRootVal() 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_15.py: -------------------------------------------------------------------------------- 1 | def inorder(tree): 2 | if tree != None: 3 | inorder(tree.getLeftChild()) 4 | print(tree.getRootVal()) 5 | inorder(tree.getRightChild()) 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_16.py: -------------------------------------------------------------------------------- 1 | def printexp(tree): 2 | sVal = "" 3 | if tree: 4 | sVal = '(' + printexp(tree.getLeftChild()) 5 | sVal = sVal + str(tree.getRootVal()) 6 | sVal = sVal + printexp(tree.getRightChild())+')' 7 | return sVal 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_17.py: -------------------------------------------------------------------------------- 1 | def __init__(self): 2 | self.heapList = [0] 3 | self.currentSize = 0 4 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_18.py: -------------------------------------------------------------------------------- 1 | def percUp(self,i): 2 | while i // 2 > 0: 3 | if self.heapList[i] < self.heapList[i // 2]: 4 | tmp = self.heapList[i // 2] 5 | self.heapList[i // 2] = self.heapList[i] 6 | self.heapList[i] = tmp 7 | i = i // 2 8 | 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_19.py: -------------------------------------------------------------------------------- 1 | def insert(self,k): 2 | self.heapList.append(k) 3 | self.currentSize = self.currentSize + 1 4 | self.percUp(self.currentSize) 5 | 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_2.py: -------------------------------------------------------------------------------- 1 | def insertLeft(root,newBranch): 2 | t = root.pop(1) 3 | if len(t) > 1: 4 | root.insert(1,[newBranch,t,[]]) 5 | else: 6 | root.insert(1,[newBranch, [], []]) 7 | return root 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_20.py: -------------------------------------------------------------------------------- 1 | def percDown(self,i): 2 | while (i * 2) <= self.currentSize: 3 | mc = self.minChild(i) 4 | if self.heapList[i] > self.heapList[mc]: 5 | tmp = self.heapList[i] 6 | self.heapList[i] = self.heapList[mc] 7 | self.heapList[mc] = tmp 8 | i = mc 9 | 10 | def minChild(self,i): 11 | if i * 2 + 1 > self.currentSize: 12 | return i * 2 13 | else: 14 | if self.heapList[i*2] < self.heapList[i*2+1]: 15 | return i * 2 16 | else: 17 | return i * 2 + 1 18 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_21.py: -------------------------------------------------------------------------------- 1 | def delMin(self): 2 | retval = self.heapList[1] 3 | self.heapList[1] = self.heapList[self.currentSize] 4 | self.currentSize = self.currentSize - 1 5 | self.heapList.pop() 6 | self.percDown(1) 7 | return retval 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_22.py: -------------------------------------------------------------------------------- 1 | def buildHeap(self,alist): 2 | i = len(alist) // 2 3 | self.currentSize = len(alist) 4 | self.heapList = [0] + alist[:] 5 | while (i > 0): self.percDown(i) 6 | i = i - 1 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_23.py: -------------------------------------------------------------------------------- 1 | class BinarySearchTree: 2 | 3 | def __init__(self): 4 | self.root = None 5 | self.size = 0 6 | 7 | def length(self): 8 | return self.size 9 | 10 | def __len__(self): 11 | return self.size 12 | 13 | def __iter__(self): 14 | return self.root.__iter__() 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_24.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self,key,val,left=None,right=None, 3 | parent=None): 4 | self.key = key 5 | self.payload = val 6 | self.leftChild = left 7 | self.rightChild = right 8 | self.parent = parent 9 | 10 | def hasLeftChild(self): 11 | return self.leftChild 12 | 13 | def hasRightChild(self): 14 | return self.rightChild 15 | 16 | def isLeftChild(self): 17 | return self.parent and \ 18 | self.parent.leftChild == self 19 | 20 | def isRightChild(self): 21 | return self.parent and \ 22 | self.parent.rightChild == self 23 | 24 | def isRoot(self): 25 | return not self.parent 26 | 27 | def isLeaf(self): 28 | return not (self.rightChild or self.leftChild) 29 | 30 | def hasAnyChildren(self): 31 | return self.rightChild or self.leftChild 32 | 33 | def hasBothChildren(self): 34 | return self.rightChild and self.leftChild 35 | 36 | def replaceNodeData(self,key,value,lc,rc): 37 | self.key = key 38 | self.payload = value 39 | self.leftChild = lc 40 | self.rightChild = rc 41 | if self.hasLeftChild(): 42 | self.leftChild.parent = self 43 | if self.hasRightChild(): 44 | self.rightChild.parent = self 45 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_25.py: -------------------------------------------------------------------------------- 1 | def put(self,key,val): 2 | if self.root: 3 | self._put(key,val,self.root) 4 | else: 5 | self.root = TreeNode(key,val) 6 | self.size = self.size + 1 7 | 8 | def _put(self,key,val,currentNode): 9 | if key < currentNode.key: 10 | if currentNode.hasLeftChild(): 11 | self._put(key,val,currentNode.leftChild) 12 | else: 13 | currentNode.leftChild = TreeNode(key,val, 14 | parent=currentNode) 15 | else: 16 | if currentNode.hasRightChild(): 17 | self._put(key,val,currentNode.rightChild) 18 | else: 19 | currentNode.rightChild = TreeNode(key,val, 20 | parent=currentNode) 21 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_26.py: -------------------------------------------------------------------------------- 1 | def __setitem__(self,k,v): 2 | self.put(k,v) 3 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_27.py: -------------------------------------------------------------------------------- 1 | def get(self,key): 2 | if self.root: 3 | res = self._get(key,self.root) 4 | if res: 5 | return res.payload 6 | else: 7 | return None 8 | else: 9 | return None 10 | 11 | def _get(self,key,currentNode): 12 | if not currentNode: 13 | return None 14 | elif currentNode.key == key: 15 | return currentNode 16 | elif key < currentNode.key: 17 | return self._get(key,currentNode.leftChild) 18 | else: 19 | return self._get(key,currentNode.rightChild) 20 | 21 | def __getitem__(self,key): 22 | return self.get(key) 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_28.py: -------------------------------------------------------------------------------- 1 | def __contains__(self,key): 2 | if self._get(key,self.root): 3 | return True 4 | else: 5 | return False 6 | 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_29.py: -------------------------------------------------------------------------------- 1 | def delete(self,key): 2 | if self.size > 1: 3 | nodeToRemove = self._get(key,self.root) 4 | if nodeToRemove: 5 | self.remove(nodeToRemove) 6 | self.size = self.size-1 7 | else: 8 | raise KeyError('Error, key not in tree') 9 | elif self.size == 1 and self.root.key == key: 10 | self.root = None 11 | self.size = self.size - 1 12 | else: 13 | raise KeyError('Error, key not in tree') 14 | 15 | def __delitem__(self,key): 16 | self.delete(key) 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_3.py: -------------------------------------------------------------------------------- 1 | def insertRight(root,newBranch): 2 | t = root.pop(2) 3 | if len(t) > 1: 4 | root.insert(2,[newBranch,[],t]) 5 | else: 6 | root.insert(2,[newBranch,[],[]]) 7 | return root 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_30.py: -------------------------------------------------------------------------------- 1 | if currentNode.isLeaf(): 2 | if currentNode == currentNode.parent.leftChild: 3 | currentNode.parent.leftChild = None 4 | else: 5 | currentNode.parent.rightChild = None 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_31.py: -------------------------------------------------------------------------------- 1 | else: # this node has one child 2 | if currentNode.hasLeftChild(): 3 | if currentNode.isLeftChild(): 4 | currentNode.leftChild.parent = currentNode.parent 5 | currentNode.parent.leftChild = currentNode.leftChild 6 | elif currentNode.isRightChild(): 7 | currentNode.leftChild.parent = currentNode.parent 8 | currentNode.parent.rightChild = currentNode.leftChild 9 | else: 10 | currentNode.replaceNodeData(currentNode.leftChild.key, 11 | currentNode.leftChild.payload, 12 | currentNode.leftChild.leftChild, 13 | currentNode.leftChild.rightChild) 14 | else: 15 | if currentNode.isLeftChild(): 16 | currentNode.rightChild.parent = currentNode.parent 17 | currentNode.parent.leftChild = currentNode.rightChild 18 | elif currentNode.isRightChild(): 19 | currentNode.rightChild.parent = currentNode.parent 20 | currentNode.parent.rightChild = currentNode.rightChild 21 | else: 22 | currentNode.replaceNodeData(currentNode.rightChild.key, 23 | currentNode.rightChild.payload, 24 | currentNode.rightChild.leftChild, 25 | currentNode.rightChild.rightChild) 26 | 27 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_32.py: -------------------------------------------------------------------------------- 1 | elif currentNode.hasBothChildren(): #interior 2 | succ = currentNode.findSuccessor() 3 | succ.spliceOut() 4 | currentNode.key = succ.key 5 | currentNode.payload = succ.payload 6 | 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_33.py: -------------------------------------------------------------------------------- 1 | def findSuccessor(self): 2 | succ = None 3 | if self.hasRightChild(): 4 | succ = self.rightChild.findMin() 5 | else: 6 | if self.parent: 7 | if self.isLeftChild(): 8 | succ = self.parent 9 | else: 10 | self.parent.rightChild = None 11 | succ = self.parent.findSuccessor() 12 | self.parent.rightChild = self 13 | return succ 14 | 15 | def findMin(self): 16 | current = self 17 | while current.hasLeftChild(): 18 | current = current.leftChild 19 | return current 20 | 21 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_34.py: -------------------------------------------------------------------------------- 1 | def spliceOut(self): 2 | if self.isLeaf(): 3 | if self.isLeftChild(): 4 | self.parent.leftChild = None 5 | else: 6 | self.parent.rightChild = None 7 | elif self.hasAnyChildren(): 8 | if self.hasLeftChild(): 9 | if self.isLeftChild(): 10 | self.parent.leftChild = self.leftChild 11 | else: 12 | self.parent.rightChild = self.leftChild 13 | self.leftChild.parent = self.parent 14 | else: 15 | if self.isLeftChild(): 16 | self.parent.leftChild = self.rightChild 17 | else: 18 | self.parent.rightChild = self.rightChild 19 | self.rightChild.parent = self.parent 20 | 21 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_36.py: -------------------------------------------------------------------------------- 1 | def __iter__(self): 2 | if self: 3 | if self.hasLeftChild(): 4 | for elem in self.leftChild: 5 | yield elem 6 | yield self.key 7 | if self.hasRightChild(): 8 | for elem in self.rightChild: 9 | yield elem 10 | 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_37.py: -------------------------------------------------------------------------------- 1 | def _put(self,key,val,currentNode): 2 | if key < currentNode.key: 3 | if currentNode.hasLeftChild(): 4 | self._put(key,val,currentNode.leftChild) 5 | else: 6 | currentNode.leftChild = TreeNode(key,val, 7 | parent=currentNode) 8 | self.updateBalance(currentNode.leftChild) else: 9 | if currentNode.hasRightChild(): 10 | self._put(key,val,currentNode.rightChild) 11 | else: 12 | currentNode.rightChild = TreeNode(key,val, 13 | parent=currentNode) 14 | self.updateBalance(currentNode.rightChild) 15 | def updateBalance(self,node): 16 | if node.balanceFactor > 1 or node.balanceFactor < -1: self.rebalance(node) return 17 | if node.parent != None: 18 | if node.isLeftChild(): 19 | node.parent.balanceFactor += 1 20 | elif node.isRightChild(): 21 | node.parent.balanceFactor -= 1 22 | 23 | if node.parent.balanceFactor != 0: 24 | self.updateBalance(node.parent) 25 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_38.py: -------------------------------------------------------------------------------- 1 | def rotateLeft(self,rotRoot): 2 | newRoot = rotRoot.rightChild rotRoot.rightChild = newRoot.leftChild 3 | if newRoot.leftChild != None: 4 | newRoot.leftChild.parent = rotRoot 5 | newRoot.parent = rotRoot.parent 6 | if rotRoot.isRoot(): 7 | self.root = newRoot 8 | else: 9 | if rotRoot.isLeftChild(): rotRoot.parent.leftChild = newRoot 10 | else: 11 | rotRoot.parent.rightChild = newRoot newRoot.leftChild = rotRoot 12 | rotRoot.parent = newRoot 13 | rotRoot.balanceFactor = rotRoot.balanceFactor + 1 \ - min(newRoot.balanceFactor, 0) 14 | newRoot.balanceFactor = newRoot.balanceFactor + 1 \ 15 | + max(rotRoot.balanceFactor, 0) 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_39.py: -------------------------------------------------------------------------------- 1 | def rebalance(self,node): 2 | if node.balanceFactor < 0: if node.rightChild.balanceFactor > 0: 3 | self.rotateRight(node.rightChild) 4 | self.rotateLeft(node) 5 | else: 6 | self.rotateLeft(node) 7 | elif node.balanceFactor > 0: if node.leftChild.balanceFactor < 0: 8 | self.rotateLeft(node.leftChild) 9 | self.rotateRight(node) 10 | else: 11 | self.rotateRight(node) 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_4.py: -------------------------------------------------------------------------------- 1 | def getRootVal(root): 2 | return root[0] 3 | 4 | def setRootVal(root,newVal): 5 | root[0] = newVal 6 | 7 | def getLeftChild(root): 8 | return root[1] 9 | 10 | def getRightChild(root): 11 | return root[2] 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_5.py: -------------------------------------------------------------------------------- 1 | class BinaryTree: 2 | def __init__(self,rootObj): 3 | self.key = rootObj 4 | self.leftChild = None 5 | self.rightChild = None 6 | 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_6.py: -------------------------------------------------------------------------------- 1 | def insertLeft(self,newNode): 2 | if self.leftChild == None: 3 | self.leftChild = BinaryTree(newNode) 4 | else: t = BinaryTree(newNode) 5 | t.left = self.leftChild 6 | self.leftChild = t 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_7.py: -------------------------------------------------------------------------------- 1 | def insertRight(self,newNode): 2 | if self.rightChild == None: 3 | self.rightChild = BinaryTree(newNode) 4 | else: 5 | t = BinaryTree(newNode) 6 | t.right = self.rightChild 7 | self.rightChild = t 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_8.py: -------------------------------------------------------------------------------- 1 | def getRightChild(self): 2 | return self.rightChild 3 | 4 | def getLeftChild(self): 5 | return self.leftChild 6 | 7 | def setRootVal(self,obj): 8 | self.key = obj 9 | 10 | def getRootVal(self): 11 | return self.key 12 | 13 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_6_9.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic import Stack 2 | from pythonds.trees import BinaryTree 3 | 4 | def buildParseTree(fpexp): 5 | fplist = fpexp.split() 6 | pStack = Stack() 7 | eTree = BinaryTree('') 8 | pStack.push(eTree) 9 | currentTree = eTree 10 | for i in fplist: 11 | if i == '(': currentTree.insertLeft('') 12 | pStack.push(currentTree) 13 | currentTree = currentTree.getLeftChild() 14 | elif i not in '+-*/)': currentTree.setRootVal(eval(i)) 15 | parent = pStack.pop() 16 | currentTree = parent 17 | elif i in '+-*/': currentTree.setRootVal(i) 18 | currentTree.insertRight('') 19 | pStack.push(currentTree) 20 | currentTree = currentTree.getRightChild() 21 | elif i == ')': currentTree = pStack.pop() 22 | else: 23 | raise ValueError("Unknown Operator: " + i) 24 | return eTree 25 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_1.py: -------------------------------------------------------------------------------- 1 | class Vertex: 2 | def __init__(self,key): 3 | self.id = key 4 | self.connectedTo = {} 5 | 6 | def addNeighbor(self,nbr,weight=0): 7 | self.connectedTo[nbr] = weight 8 | 9 | def __str__(self): 10 | return str(self.id) + ' connectedTo: ' 11 | + str([x.id for x in self.connectedTo]) 12 | 13 | def getConnections(self): 14 | return self.connectedTo.keys() 15 | 16 | def getId(self): 17 | return self.id 18 | 19 | def getWeight(self,nbr): 20 | return self.connectedTo[nbr] 21 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_10.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import Graph 2 | class DFSGraph(Graph): 3 | def __init__(self): 4 | super().__init__() 5 | self.time = 0 6 | 7 | def dfs(self): 8 | for aVertex in self: aVertex.setColor('white') 9 | aVertex.setPred(-1) 10 | for aVertex in self: if aVertex.getColor() == 'white': 11 | self.dfsvisit(aVertex) 12 | 13 | def dfsvisit(self,startVertex): 14 | startVertex.setColor('gray') 15 | self.time += 1 16 | startVertex.setDiscovery(self.time) 17 | for nextVertex in startVertex.getConnections(): if nextVertex.getColor() == 'white': 18 | nextVertex.setPred(startVertex) 19 | self.dfsvisit(nextVertex) 20 | startVertex.setColor('black') 21 | self.time += 1 22 | startVertex.setFinish(self.time) 23 | 24 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_11.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import PriorityQueue, Graph, Vertex 2 | def dijkstra(aGraph,start): 3 | pq = PriorityQueue() 4 | start.setDistance(0) 5 | pq.buildHeap([(v.getDistance(),v) for v in aGraph]) 6 | while not pq.isEmpty(): currentVert = pq.delMin() 7 | for nextVert in currentVert.getConnections(): newDist = currentVert.getDistance() \ 8 | + currentVert.getWeight(nextVert) 9 | if newDist < nextVert.getDistance(): 10 | nextVert.setDistance( newDist ) 11 | nextVert.setPred(currentVert) 12 | pq.decreaseKey(nextVert,newDist) 13 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_12.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import PriorityQueue, Graph, Vertex 2 | def prim(G,start): 3 | pq = PriorityQueue() 4 | for v in G: 5 | v.setDistance(sys.maxsize) 6 | v.setPred(None) 7 | start.setDistance(0) 8 | pq.buildHeap([(v.getDistance(),v) for v in G]) 9 | while not pq.isEmpty(): 10 | currentVert = pq.delMin() 11 | for nextVert in currentVert.getConnections(): 12 | newCost = currentVert.getWeight(nextVert) \ 13 | + currentVert.getDistance() 14 | if v in pq and newCost 0): currentVert = vertQueue.dequeue() 9 | for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): 10 | nbr.setColor('gray') 11 | nbr.setDistance(currentVert.getDistance() + 1) 12 | nbr.setPred(currentVert) 13 | vertQueue.enqueue(nbr) 14 | currentVert.setColor('black') 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_5.py: -------------------------------------------------------------------------------- 1 | def traverse(y): 2 | x = y 3 | while (x.getPred()): 4 | print(x.getId()) 5 | x = x.getPred() 6 | print(x.getId()) 7 | 8 | traverse(g.getVertex('sage')) 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_6.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import Graph 2 | def knightGraph(bdSize): 3 | ktGraph = Graph() 4 | for row in range(bdSize): 5 | for col in range(bdSize): 6 | nodeId = posToNodeId(row,col,bdSize) 7 | newPositions = genLegalMoves(row,col,bdSize) 8 | for e in newPositions: 9 | nid = posToNodeId(e[0],e[1]) 10 | ktGraph.addEdge(nodeId,nid) 11 | return ktGraph 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_7.py: -------------------------------------------------------------------------------- 1 | def genLegalMoves(x,y,bdSize): 2 | newMoves = [] 3 | moveOffsets = [(-1,-2),(-1,2),(-2,-1),(-2,1), 4 | ( 1,-2),( 1,2),( 2,-1),( 2,1)]: 5 | for i in moveOffsets: 6 | newX = x + i[0] 7 | newY = y + i[1] 8 | if legalCoord(newX,bdSize) and \ 9 | legalCoord(newY,bdSize): 10 | newMoves.append((newX,newY)) 11 | return newMoves 12 | 13 | def legalCoord(x,bdSize): 14 | if x >= 0 and x < bdSize: 15 | return True 16 | else: 17 | return False 18 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_8.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import Graph, Vertex 2 | def knightTour(n,path,u,limit): 3 | u.setColor('gray') 4 | path.append(u) 5 | if n < limit: 6 | nbrList = list(u.getConnections()) i = 0 7 | done = False 8 | while i < len(nbrList) and not done: 9 | if nbrList[i].getColor() == 'white': 10 | done = knightTour(n+1, path, 11 | nbrList[i], 12 | limit) 13 | i = i + 1 14 | if not done: # prepare to backtrack 15 | path.pop() 16 | u.setColor('white') 17 | else: 18 | done = True 19 | return done 20 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_7_9.py: -------------------------------------------------------------------------------- 1 | def orderByAvail(n): 2 | resList = [] 3 | for v in n.geConnections(): 4 | if v.getColor() == 'white': 5 | c = 0 6 | for w in v.getConnections(): 7 | if w.getColor() == 'white': 8 | c = c + 1 9 | resList.append((c,v)) 10 | resList.sort(key=lambda x: x[0]) return [y[1] for y in resList] 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_1.py: -------------------------------------------------------------------------------- 1 | class ArrayList: 2 | 3 | def __init__(self, ): 4 | self.sizeExponent = 0 5 | self.maxSize = 0 6 | self.lastIndex = 0 7 | self.myArray = [] 8 | 9 | def append(self,val): 10 | if self.lastIndex > self.maxSize-1: self.__resize() 11 | self.myArray[self.lastIndex] = val 12 | self.lastIndex += 1 13 | 14 | 15 | def __resize(self): 16 | newsize = 2 ** self.sizeExponent 17 | print("newsize = ", newsize) 18 | newarray = [0]*newsize 19 | for i in range(self.maxSize): newarray[i] = self.myArray[i] 20 | 21 | self.maxSize = newsize 22 | self.myArray = newarray 23 | self.sizeExponent += 1 24 | 25 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_10.py: -------------------------------------------------------------------------------- 1 | def RSAgenKeys(p,q): 2 | n = p * q 3 | pqminus = (p-1) * (q-1) 4 | e = int(random.random() * n) 5 | while gcd(pqminus,e) != 1: 6 | e = int(random.random() * n) 7 | d,a,b = ext_gcd(pqminus,e) 8 | if b < 0: 9 | d = pqminus+b 10 | else: 11 | d = b 12 | return ((e,d,n)) 13 | 14 | def RSAencrypt(m,e,n): 15 | ndigits = len(str(n)) 16 | chunkSize = ndigits - 1 17 | chunks = toChunks(m,chunkSize) 18 | encList = [] 19 | for messChunk in chunks: 20 | print messChunk 21 | c = modexp(messChunk,e,n) 22 | encList.append(c) 23 | return encList 24 | 25 | def RSAdecrypt(clist,d,n): 26 | rList = [] 27 | for c in clist: 28 | m = modexp(c,d,n) 29 | rList.append(m) 30 | return rList 31 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_11.py: -------------------------------------------------------------------------------- 1 | def toChunks(m,chunkSize): 2 | byteMess = bytes(m,'utf-8') 3 | hexString = '' 4 | for b in byteMess: 5 | hexString = hexString + ("%02x" % b) 6 | 7 | numChunks = len(hexString) // chunkSize 8 | chunkList = [] 9 | for i in range(0,numChunks*chunkSize+1,chunkSize): 10 | chunkList.append(hexString[i:i+chunkSize]) 11 | chunkList = [eval('0x'+x) for x in chunkList if x] 12 | return chunkList 13 | 14 | 15 | def chunksToPlain(clist,chunkSize): 16 | hexList = [] 17 | for c in clist: 18 | hexString = hex(c)[2:] 19 | clen = len(hexString) 20 | hexList.append('0' * ((chunkSize - clen) % 2) 21 | + hexString) 22 | 23 | hstring = "".join(hexList) 24 | messArray = bytearray.fromhex(hstring) 25 | return messArray.decode('utf-8') 26 | 27 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_12.py: -------------------------------------------------------------------------------- 1 | class HeaderNode: 2 | def __init__(self): 3 | self.next = None 4 | self.down = None 5 | 6 | def getNext(self): 7 | return self.next 8 | 9 | def getDown(self): 10 | return self.down 11 | 12 | def setNext(self,newnext): 13 | self.next = newnext 14 | 15 | def setDown(self,newdown): 16 | self.down = newdown 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_13.py: -------------------------------------------------------------------------------- 1 | class DataNode: 2 | def __init__(self,key,value): 3 | self.key = key 4 | self.data = value 5 | self.next = None 6 | self.down = None 7 | 8 | def getKey(self): 9 | return self.key 10 | 11 | def getData(self): 12 | return self.data 13 | 14 | def getNext(self): 15 | return self.next 16 | 17 | def getDown(self): 18 | return self.down 19 | 20 | def setData(self,newdata): 21 | self.data = newdata 22 | 23 | def setNext(self,newnext): 24 | self.next = newnext 25 | 26 | def setDown(self,newdown): 27 | self.down = newdown 28 | 29 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_14.py: -------------------------------------------------------------------------------- 1 | class SkipList: 2 | def __init__(self): 3 | self.head = None 4 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_15.py: -------------------------------------------------------------------------------- 1 | def search(self,key): 2 | current = self.head 3 | found = False 4 | stop = False 5 | while not found and not stop: 6 | if current == None: 7 | stop = True 8 | else: 9 | if current.getNext() == None: 10 | current = current.getDown() 11 | else: 12 | if current.getNext().getKey() == key: 13 | found = True 14 | else: 15 | if key < current.getNext().getKey(): 16 | current = current.getDown() 17 | else: 18 | current = current.getNext() 19 | if found: 20 | return current.getNext().getData() 21 | else: 22 | return None 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_16.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | def flip(): 3 | return randrange(2) 4 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_17.py: -------------------------------------------------------------------------------- 1 | def insert(self,key,data): 2 | if self.head == None: 3 | self.head = HeaderNode() 4 | temp = DataNode(key,data) 5 | self.head.setNext(temp) 6 | top = temp 7 | while flip() == 1: 8 | newhead = HeaderNode() 9 | temp = DataNode(key,data) 10 | temp.setDown(top) 11 | newhead.setNext(temp) 12 | newhead.setDown(self.head) 13 | self.head = newhead 14 | top = temp 15 | else: 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_18.py: -------------------------------------------------------------------------------- 1 | towerStack = Stack() 2 | current = self.head 3 | stop = False 4 | while not stop: 5 | if current == None: 6 | stop = True 7 | else: 8 | if current.getNext() == None: 9 | towerStack.push(current) 10 | current = current.getDown() 11 | else: 12 | if current.getNext().getKey() > key: 13 | towerStack.push(current) 14 | current = current.getDown() 15 | else: 16 | current = current.getNext() 17 | 18 | lowestLevel = towerStack.pop() 19 | temp = DataNode(key,data) 20 | temp.setNext(lowestLevel.getNext()) 21 | lowestLevel.setNext(temp) 22 | top = temp 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_19.py: -------------------------------------------------------------------------------- 1 | while flip() == 1: 2 | if towerStack.isEmpty(): 3 | newhead = HeaderNode() 4 | temp = DataNode(key,data) 5 | temp.setDown(top) 6 | newhead.setNext(temp) 7 | newhead.setDown(self.head) 8 | self.head = newhead 9 | top = temp 10 | else: 11 | nextLevel = towerStack.pop() 12 | temp = DataNode(key,data) 13 | temp.setDown(top) 14 | temp.setNext(nextLevel.getNext()) 15 | nextLevel.setNext(temp) 16 | top = temp 17 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_2.py: -------------------------------------------------------------------------------- 1 | def __getitem__(self,idx): 2 | if idx < self.lastIndex: 3 | return self.myArray[idx] 4 | else: 5 | raise LookupError('index out of bounds') 6 | 7 | def __setitem__(self,idx,val): 8 | if idx < self.lastIndex: 9 | self.myArray[idx] = val 10 | else: 11 | raise LookupError('index out of bounds') 12 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_20.py: -------------------------------------------------------------------------------- 1 | class Map: 2 | def __init__(self): 3 | self.collection=SkipList() 4 | 5 | def put(self,key,value): 6 | self.collection.insert(key,value) 7 | 8 | def get(self,key): 9 | return self.collection.search(key) 10 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_21.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import Image 4 | def simpleQuant(): 5 | im = Image.open('bubbles.jpg') 6 | w,h = im.size 7 | for row in range(h): 8 | for col in range(w): 9 | r,g,b = im.getpixel((col,row)) 10 | r = r // 36 * 36 11 | g = g // 42 * 42 12 | b = b // 42 * 42 13 | im.putpixel((col,row),(r,g,b)) 14 | im.show() 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_22.py: -------------------------------------------------------------------------------- 1 | def buildAndDisplay(): 2 | im = Image.open('bubbles.jpg') 3 | w,h = im.size 4 | ot = OctTree() 5 | for row in range(0,h): for col in range(0,w): 6 | r,g,b = im.getpixel((col,row)) 7 | ot.insert(r,g,b) 8 | ot.reduce(256) # reduce to 256 colors 9 | for row in range(0,h): 10 | for col in range(0,w): 11 | r,g,b = im.getpixel((col,row)) 12 | nr,ng,nb = ot.find(r,g,b) im.putpixel((col,row),(nr,ng,nb)) # replace pixel with new quantized values 13 | 14 | im.show() 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_23.py: -------------------------------------------------------------------------------- 1 | class OctTree: 2 | def __init__(self): 3 | self.root = None 4 | self.maxLevel = 5 5 | self.numLeaves = 0 6 | self.leafList = [] 7 | 8 | def insert(self,r,g,b): 9 | if not self.root: 10 | self.root = self.otNode(outer=self) 11 | self.root.insert(r,g,b,0,self) 12 | 13 | def find(self,r,g,b): 14 | if self.root: 15 | return self.root.find(r,g,b,0) 16 | 17 | def reduce(self,maxCubes): while len(self.leafList) > maxCubes: 18 | smallest = self.findMinCube() 19 | smallest.parent.merge() self.leafList.append(smallest.parent) 20 | self.numLeaves = self.numLeaves + 1 21 | 22 | def findMinCube(self): 23 | minCount = sys.maxint 24 | maxLev = 0 25 | minCube = None 26 | for i in self.leafList: 27 | if i.count <= minCount and i.level >= maxLev: 28 | minCube = i 29 | minCount = i.count 30 | maxLev = i.level 31 | return minCube 32 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_24.py: -------------------------------------------------------------------------------- 1 | class otNode: 2 | def __init__(self,parent=None,level=0,outer=None): 3 | self.red = 0 4 | self.green = 0 5 | self.blue = 0 6 | self.count = 0 7 | self.parent = parent 8 | self.level = level 9 | self.oTree = outer 10 | self.children = [None]*8 11 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_25.py: -------------------------------------------------------------------------------- 1 | def insert(self,r,g,b,level,outer): 2 | if level < self.oTree.maxLevel: 3 | idx = self.computeIndex(r,g,b,level) 4 | if self.children[idx] == None: 5 | self.children[idx] = outer.otNode(parent=self, 6 | level=level+1, 7 | outer=outer) 8 | self.children[idx].insert(r,g,b,level+1,outer) 9 | else: 10 | if self.count == 0: 11 | self.oTree.numLeaves = self.oTree.numLeaves + 1 12 | self.oTree.leafList.append(self) 13 | self.red += r 14 | self.green += g 15 | self.blue += b 16 | self.count = self.count + 1 17 | 18 | def computeIndex(self,r,g,b,level): shift = 8 - level 19 | rc = r >> shift-2 & 0x4 20 | gc = g >> shift-1 & 0x2 21 | bc = b >> shift & 0x1 22 | return(rc | gc | bc) 23 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_26.py: -------------------------------------------------------------------------------- 1 | def find(self,r,g,b,level): 2 | if level < self.oTree.maxLevel: 3 | idx = self.computeIndex(r,g,b,level) 4 | if self.children[idx]: 5 | return self.children[idx].find(r,g,b,level+1) 6 | elif self.count > 0: 7 | return ((self.red//self.count, 8 | self.green//self.count, 9 | self.blue//self.count)) else: 10 | print("error: No leaf node for this color") 11 | else: 12 | return ((self.red//self.count, 13 | self.green//self.count, 14 | self.blue//self.count)) -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_27.py: -------------------------------------------------------------------------------- 1 | def merge(self): 2 | for i in self.children: 3 | if i: 4 | if i.count > 0: 5 | self.oTree.leafList.remove(i) 6 | self.oTree.numLeaves -= 1 7 | else: 8 | print("Recursively Merging non-leaf...") 9 | i.merge() 10 | self.count += i.count 11 | self.red += i.red 12 | self.green += i.green 13 | self.blue += i.blue 14 | for i in range(8): 15 | self.children[i] = None 16 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_28.py: -------------------------------------------------------------------------------- 1 | def simpleMatcher(pattern, text): 2 | starti = 0 #tracks the start of each attempt 3 | i = 0 #index into text 4 | j = 0 #index into pattern 5 | match = False 6 | stop = False 7 | while not match and not stop: 8 | if text[i] == pattern[j]: 9 | i = i+1 10 | j = j+1 11 | else: 12 | starti = starti + 1 #shift to right 13 | i = starti 14 | j = 0 15 | 16 | if j == len(pattern): 17 | match = True 18 | else: 19 | if i == len(text): 20 | stop = True 21 | 22 | if match: 23 | return i-j 24 | else: 25 | return -1 26 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_29.py: -------------------------------------------------------------------------------- 1 | def mismatchLinks(pattern): 2 | augPattern = "0"+pattern 3 | links = {} 4 | links[1] = 0 5 | for k in range(2,len(augPattern)): 6 | s = links[k-1] 7 | stop = False 8 | while s>=1 and not stop: 9 | if augPattern[s] == augPattern[k-1]: 10 | stop = True 11 | else: 12 | s = links[s] 13 | links[k] = s+1 14 | return links 15 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_3.py: -------------------------------------------------------------------------------- 1 | def insert(self,idx,val): 2 | if self.lastIndex > self.maxSize - 1: 3 | self.__resize() 4 | for i in range(self.lastIndex,idx-1,-1): self.myArray[i+1] = self.myArray[i] 5 | self.lastIndex += 1 6 | self.myArray[idx] = val 7 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_4.py: -------------------------------------------------------------------------------- 1 | def encrypt(m): 2 | s = 'abcdefghijklmnopqrstuvwxyz' 3 | n = '' 4 | for i in m: 5 | j = (s.find(i)+13)%26 6 | n = n + s[j] 7 | return n 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_5.py: -------------------------------------------------------------------------------- 1 | def decrypt(m,k): 2 | s = 'abcdefghijklmnopqrstuvwxyz' 3 | n = '' 4 | for i in m: 5 | j = (s.find(i)26-k)%26 6 | n = n + s[j] 7 | return n 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_6.py: -------------------------------------------------------------------------------- 1 | def modexp(x,n,p): 2 | if n == 0: 3 | return 1 4 | t = (x*x)%p 5 | tmp = modexp(t,n//2,p) 6 | if n%2 != 0: 7 | tmp = (tmp * x) % p 8 | return tmp 9 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_7.py: -------------------------------------------------------------------------------- 1 | def gcd(a,b): 2 | if b == 0: 3 | return a 4 | elif a < b: 5 | return gcd(b,a) 6 | else: 7 | return gcd(a-b,b) 8 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_8.py: -------------------------------------------------------------------------------- 1 | def gcd(a,b): 2 | if b == 0: 3 | return a 4 | else: 5 | return gcd(b, a % b) 6 | -------------------------------------------------------------------------------- /pythonds/Listings/listing_8_9.py: -------------------------------------------------------------------------------- 1 | def ext_gcd(x,y): 2 | if y == 0: 3 | return(x,1,0) 4 | else: 5 | (d,a,b) = ext_gcd(y, x%y) 6 | return(d,b,a-(x//y)*b) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms.zip -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter1/fraction.py: -------------------------------------------------------------------------------- 1 | def gcd(m,n): 2 | while m%n != 0: 3 | oldm = m 4 | oldn = n 5 | 6 | m = oldn 7 | n = oldm%oldn 8 | return n 9 | 10 | class Fraction: 11 | def __init__(self,top,bottom): 12 | self.num = top 13 | self.den = bottom 14 | 15 | def __str__(self): 16 | return str(self.num)+"/"+str(self.den) 17 | 18 | def show(self): 19 | print(self.num,"/",self.den) 20 | 21 | def __add__(self,otherfraction): 22 | newnum = self.num*otherfraction.den + \ 23 | self.den*otherfraction.num 24 | newden = self.den * otherfraction.den 25 | common = gcd(newnum,newden) 26 | return Fraction(newnum//common,newden//common) 27 | 28 | def __eq__(self, other): 29 | firstnum = self.num * other.den 30 | secondnum = other.num * self.den 31 | 32 | return firstnum == secondnum 33 | 34 | x = Fraction(1,2) 35 | y = Fraction(2,3) 36 | print(x+y) 37 | print(x == y) 38 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter3/baseconverter.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.stack import Stack 2 | 3 | def baseConverter(decNumber,base): 4 | digits = "0123456789ABCDEF" 5 | 6 | remstack = Stack() 7 | 8 | while decNumber > 0: 9 | rem = decNumber % base 10 | remstack.push(rem) 11 | decNumber = decNumber // base 12 | 13 | newString = "" 14 | while not remstack.isEmpty(): 15 | newString = newString + digits[remstack.pop()] 16 | 17 | return newString 18 | 19 | print(baseConverter(25,2)) 20 | print(baseConverter(25,16)) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter3/hotpotato.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.queue import Queue 2 | 3 | def hotPotato(namelist, num): 4 | simqueue = Queue() 5 | for name in namelist: 6 | simqueue.enqueue(name) 7 | 8 | while simqueue.size() > 1: 9 | for i in range(num): 10 | simqueue.enqueue(simqueue.dequeue()) 11 | 12 | simqueue.dequeue() 13 | 14 | return simqueue.dequeue() 15 | 16 | print(hotPotato(["Bill","David","Susan","Jane","Kent","Brad"],7)) 17 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter3/palindromechecker.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.deque import Deque 2 | 3 | def palchecker(aString): 4 | chardeque = Deque() 5 | 6 | for ch in aString: 7 | chardeque.addRear(ch) 8 | 9 | stillEqual = True 10 | 11 | while chardeque.size() > 1 and stillEqual: 12 | first = chardeque.removeFront() 13 | last = chardeque.removeRear() 14 | if first != last: 15 | stillEqual = False 16 | 17 | return stillEqual 18 | 19 | print(palchecker("lsdkjfskf")) 20 | print(palchecker("radar")) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter3/parcheckers.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.stack import Stack 2 | 3 | def parChecker(symbolString): 4 | s = Stack() 5 | balanced = True 6 | index = 0 7 | while index < len(symbolString) and balanced: 8 | symbol = symbolString[index] 9 | if symbol == "(": 10 | s.push(symbol) 11 | else: 12 | if s.isEmpty(): 13 | balanced = False 14 | else: 15 | s.pop() 16 | 17 | index = index + 1 18 | 19 | if balanced and s.isEmpty(): 20 | return True 21 | else: 22 | return False 23 | 24 | print(parChecker('((()))')) 25 | print(parChecker('(()')) 26 | 27 | def parChecker(symbolString): 28 | s = Stack() 29 | balanced = True 30 | index = 0 31 | while index < len(symbolString) and balanced: 32 | symbol = symbolString[index] 33 | if symbol in "([{": 34 | s.push(symbol) 35 | else: 36 | if s.isEmpty(): 37 | balanced = False 38 | else: 39 | top = s.pop() 40 | if not matches(top,symbol): 41 | balanced = False 42 | index = index + 1 43 | if balanced and s.isEmpty(): 44 | return True 45 | else: 46 | return False 47 | 48 | def matches(open,close): 49 | opens = "([{" 50 | closers = ")]}" 51 | return opens.index(open) == closers.index(close) 52 | 53 | 54 | print(parChecker('{{([][])}()}')) 55 | print(parChecker('[{()]')) 56 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter3/stacktest.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.stack import Stack 2 | 3 | s = Stack() 4 | 5 | s.push(33) 6 | print(s.size()) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/makingchange.py: -------------------------------------------------------------------------------- 1 | def dpMakeChange(coinValueList,change,minCoins,coinsUsed): 2 | for cents in range(change+1): 3 | coinCount = cents 4 | newCoin = 1 5 | for j in [c for c in coinValueList if c <= cents]: 6 | if minCoins[cents-j] + 1 < coinCount: 7 | coinCount = minCoins[cents-j]+1 8 | newCoin = j 9 | minCoins[cents] = coinCount 10 | coinsUsed[cents] = newCoin 11 | return minCoins[change] 12 | 13 | def printCoins(coinsUsed,change): 14 | coin = change 15 | while coin > 0: 16 | thisCoin = coinsUsed[coin] 17 | print(thisCoin) 18 | coin = coin - thisCoin 19 | 20 | def main(): 21 | amnt = 63 22 | clist = [1,5,10,21,25] 23 | coinsUsed = [0]*(amnt+1) 24 | coinCount = [0]*(amnt+1) 25 | 26 | print("Making change for",amnt,"requires") 27 | print(dpMakeChange(clist,amnt,coinCount,coinsUsed),"coins") 28 | print("They are:") 29 | printCoins(coinsUsed,amnt) 30 | print("The used list is as follows:") 31 | print(coinsUsed) 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/maze2.txt: -------------------------------------------------------------------------------- 1 | ++++++++++++++++++++++ 2 | + + ++ ++ + 3 | + ++++++++++ 4 | + + ++ ++++ +++ ++ 5 | + + + + ++ +++ + 6 | + ++ ++ + + 7 | +++++ + + ++ + + 8 | +++++ +++ + + ++ + 9 | + + + S+ + + 10 | +++++ + + + + + + 11 | ++++++++++++++++++++++ 12 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/recursiveconversion.py: -------------------------------------------------------------------------------- 1 | def toStr(n,base): 2 | convertString = "0123456789ABCDEF" 3 | if n < base: 4 | return convertString[n] 5 | else: 6 | return toStr(n//base,base) + convertString[n%base] 7 | 8 | print(toStr(1453,16)) 9 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/recursivelistsummation.py: -------------------------------------------------------------------------------- 1 | def listsum(numList): 2 | if len(numList) == 1: 3 | return numList[0] 4 | else: 5 | return numList[0] + listsum(numList[1:]) 6 | 7 | print(listsum([1,3,5,7,9])) 8 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/recursivespiral.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | myTurtle = turtle.Turtle() 4 | myWin = turtle.Screen() 5 | 6 | def drawSpiral(myTurtle, lineLen): 7 | if lineLen > 0: 8 | myTurtle.forward(lineLen) 9 | myTurtle.right(90) 10 | drawSpiral(myTurtle,lineLen-5) 11 | 12 | drawSpiral(myTurtle,100) 13 | myWin.exitonclick() -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/recursivetree.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def tree(branchLen,t): 4 | if branchLen > 5: 5 | t.forward(branchLen) 6 | t.right(20) 7 | tree(branchLen-15,t) 8 | t.left(40) 9 | tree(branchLen-15,t) 10 | t.right(20) 11 | t.backward(branchLen) 12 | 13 | def main(): 14 | t = turtle.Turtle() 15 | myWin = turtle.Screen() 16 | t.left(90) 17 | t.up() 18 | t.backward(100) 19 | t.down() 20 | t.color("green") 21 | tree(75,t) 22 | myWin.exitonclick() 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/recursivetriangle.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def drawTriangle(points,color,myTurtle): 4 | myTurtle.fillcolor(color) 5 | myTurtle.up() 6 | myTurtle.goto(points[0][0],points[0][1]) 7 | myTurtle.down() 8 | myTurtle.begin_fill() 9 | myTurtle.goto(points[1][0],points[1][1]) 10 | myTurtle.goto(points[2][0],points[2][1]) 11 | myTurtle.goto(points[0][0],points[0][1]) 12 | myTurtle.end_fill() 13 | 14 | def getMid(p1,p2): 15 | return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2) 16 | 17 | def sierpinski(points,degree,myTurtle): 18 | colormap = ['blue','red','green','white','yellow', 19 | 'violet','orange'] 20 | drawTriangle(points,colormap[degree],myTurtle) 21 | if degree > 0: 22 | sierpinski([points[0], 23 | getMid(points[0], points[1]), 24 | getMid(points[0], points[2])], 25 | degree-1, myTurtle) 26 | sierpinski([points[1], 27 | getMid(points[0], points[1]), 28 | getMid(points[1], points[2])], 29 | degree-1, myTurtle) 30 | sierpinski([points[2], 31 | getMid(points[2], points[1]), 32 | getMid(points[0], points[2])], 33 | degree-1, myTurtle) 34 | 35 | def main(): 36 | myTurtle = turtle.Turtle() 37 | myWin = turtle.Screen() 38 | myPoints = [[-100,-50],[0,100],[100,-50]] 39 | sierpinski(myPoints,3,myTurtle) 40 | myWin.exitonclick() 41 | 42 | main() 43 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter4/towerofhanoi.py: -------------------------------------------------------------------------------- 1 | def moveTower(height,fromPole, toPole, withPole): 2 | if height >= 1: 3 | moveTower(height-1,fromPole,withPole,toPole) 4 | moveDisk(fromPole,toPole) 5 | moveTower(height-1,withPole,toPole,fromPole) 6 | 7 | def moveDisk(fp,tp): 8 | print("moving disk from",fp,"to",tp) 9 | 10 | moveTower(3,"A","B","C") 11 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/binarysearch.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist, item): 2 | first = 0 3 | last = len(alist)-1 4 | found = False 5 | 6 | while first<=last and not found: 7 | midpoint = (first + last)//2 8 | if alist[midpoint] == item: 9 | found = True 10 | else: 11 | if item < alist[midpoint]: 12 | last = midpoint-1 13 | else: 14 | first = midpoint+1 15 | 16 | return found 17 | 18 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] 19 | print(binarySearch(testlist, 3)) 20 | print(binarySearch(testlist, 13)) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/binarysearchrecursive.py: -------------------------------------------------------------------------------- 1 | def binarySearch(alist, item): 2 | if len(alist) == 0: 3 | return False 4 | else: 5 | midpoint = len(alist)//2 6 | if alist[midpoint]==item: 7 | return True 8 | else: 9 | if itemalist[i+1]: 5 | temp = alist[i] 6 | alist[i] = alist[i+1] 7 | alist[i+1] = temp 8 | 9 | alist = [54,26,93,17,77,31,44,55,20] 10 | bubbleSort(alist) 11 | print(alist) 12 | 13 | def shortBubbleSort(alist): 14 | exchanges = True 15 | passnum = len(alist)-1 16 | while passnum > 0 and exchanges: 17 | exchanges = False 18 | for i in range(passnum): 19 | if alist[i]>alist[i+1]: 20 | exchanges = True 21 | temp = alist[i] 22 | alist[i] = alist[i+1] 23 | alist[i+1] = temp 24 | passnum = passnum-1 25 | 26 | alist=[20,30,40,90,50,60,70,80,100,110] 27 | shortBubbleSort(alist) 28 | print(alist) 29 | 30 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/insertionsort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(alist): 2 | for index in range(1,len(alist)): 3 | 4 | currentvalue = alist[index] 5 | position = index 6 | 7 | while position>0 and alist[position-1]>currentvalue: 8 | alist[position]=alist[position-1] 9 | position = position-1 10 | 11 | alist[position]=currentvalue 12 | 13 | alist = [54,26,93,17,77,31,44,55,20] 14 | insertionSort(alist) 15 | print(alist) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/mergesort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(alist): 2 | print("Splitting ",alist) 3 | if len(alist)>1: 4 | mid = len(alist)//2 5 | lefthalf = alist[:mid] 6 | righthalf = alist[mid:] 7 | 8 | mergeSort(lefthalf) 9 | mergeSort(righthalf) 10 | 11 | i=0 12 | j=0 13 | k=0 14 | while i item: 10 | stop = True 11 | else: 12 | pos = pos+1 13 | 14 | return found 15 | 16 | testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] 17 | print(orderedSequentialSearch(testlist, 3)) 18 | print(orderedSequentialSearch(testlist, 13)) 19 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/quicksort.py: -------------------------------------------------------------------------------- 1 | def quickSort(alist): 2 | quickSortHelper(alist,0,len(alist)-1) 3 | 4 | def quickSortHelper(alist,first,last): 5 | if first= pivotvalue and \ 27 | rightmark >= leftmark: 28 | rightmark = rightmark -1 29 | 30 | if rightmark < leftmark: 31 | done = True 32 | else: 33 | temp = alist[leftmark] 34 | alist[leftmark] = alist[rightmark] 35 | alist[rightmark] = temp 36 | 37 | temp = alist[first] 38 | alist[first] = alist[rightmark] 39 | alist[rightmark] = temp 40 | 41 | 42 | return rightmark 43 | 44 | alist = [54,26,93,17,77,31,44,55,20] 45 | quickSort(alist) 46 | print(alist) 47 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/selectionsort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(alist): 2 | for fillslot in range(len(alist)-1,0,-1): 3 | positionOfMax=0 4 | for location in range(1,fillslot+1): 5 | if alist[location]>alist[positionOfMax]: 6 | positionOfMax = location 7 | 8 | temp = alist[fillslot] 9 | alist[fillslot] = alist[positionOfMax] 10 | alist[positionOfMax] = temp 11 | 12 | alist = [54,26,93,17,77,31,44,55,20] 13 | selectionSort(alist) 14 | print(alist) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/sequentialsearch.py: -------------------------------------------------------------------------------- 1 | def sequentialSearch(alist, item): 2 | pos = 0 3 | found = False 4 | 5 | while pos < len(alist) and not found: 6 | if alist[pos] == item: 7 | found = True 8 | else: 9 | pos = pos+1 10 | 11 | return found 12 | 13 | testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0] 14 | print(sequentialSearch(testlist, 3)) 15 | print(sequentialSearch(testlist, 13)) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter5/shellsort.py: -------------------------------------------------------------------------------- 1 | def shellSort(alist): 2 | sublistcount = len(alist)//2 3 | while sublistcount > 0: 4 | 5 | for startposition in range(sublistcount): 6 | gapInsertionSort(alist,startposition,sublistcount) 7 | 8 | print("After increments of size",sublistcount, 9 | "The list is",alist) 10 | 11 | sublistcount = sublistcount // 2 12 | 13 | def gapInsertionSort(alist,start,gap): 14 | for i in range(start+gap,len(alist),gap): 15 | 16 | currentvalue = alist[i] 17 | position = i 18 | 19 | while position>=gap and alist[position-gap]>currentvalue: 20 | alist[position]=alist[position-gap] 21 | position = position-gap 22 | 23 | alist[position]=currentvalue 24 | 25 | alist = [54,26,93,17,77,31,44,55,20] 26 | shellSort(alist) 27 | print(alist) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter6/binarytreelist.py: -------------------------------------------------------------------------------- 1 | def BinaryTree(r): 2 | return [r, [], []] 3 | 4 | def insertLeft(root,newBranch): 5 | t = root.pop(1) 6 | if len(t) > 1: 7 | root.insert(1,[newBranch,t,[]]) 8 | else: 9 | root.insert(1,[newBranch, [], []]) 10 | return root 11 | 12 | def insertRight(root,newBranch): 13 | t = root.pop(2) 14 | if len(t) > 1: 15 | root.insert(2,[newBranch,[],t]) 16 | else: 17 | root.insert(2,[newBranch,[],[]]) 18 | return root 19 | 20 | def getRootVal(root): 21 | return root[0] 22 | 23 | def setRootVal(root,newVal): 24 | root[0] = newVal 25 | 26 | def getLeftChild(root): 27 | return root[1] 28 | 29 | def getRightChild(root): 30 | return root[2] 31 | 32 | r = BinaryTree(3) 33 | insertLeft(r,4) 34 | insertLeft(r,5) 35 | insertRight(r,6) 36 | insertRight(r,7) 37 | l = getLeftChild(r) 38 | print(l) 39 | 40 | setRootVal(l,9) 41 | print(r) 42 | insertLeft(l,11) 43 | print(r) 44 | print(getRightChild(getRightChild(r))) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter6/binarytreenoderef.py: -------------------------------------------------------------------------------- 1 | 2 | class BinaryTree: 3 | def __init__(self,rootObj): 4 | self.key = rootObj 5 | self.leftChild = None 6 | self.rightChild = None 7 | 8 | def insertLeft(self,newNode): 9 | if self.leftChild == None: 10 | self.leftChild = BinaryTree(newNode) 11 | else: 12 | t = BinaryTree(newNode) 13 | t.leftChild = self.leftChild 14 | self.leftChild = t 15 | 16 | def insertRight(self,newNode): 17 | if self.rightChild == None: 18 | self.rightChild = BinaryTree(newNode) 19 | else: 20 | t = BinaryTree(newNode) 21 | t.rightChild = self.rightChild 22 | self.rightChild = t 23 | 24 | 25 | def getRightChild(self): 26 | return self.rightChild 27 | 28 | def getLeftChild(self): 29 | return self.leftChild 30 | 31 | def setRootVal(self,obj): 32 | self.key = obj 33 | 34 | def getRootVal(self): 35 | return self.key 36 | 37 | 38 | r = BinaryTree('a') 39 | print(r.getRootVal()) 40 | print(r.getLeftChild()) 41 | r.insertLeft('b') 42 | print(r.getLeftChild()) 43 | print(r.getLeftChild().getRootVal()) 44 | r.insertRight('c') 45 | print(r.getRightChild()) 46 | print(r.getRightChild().getRootVal()) 47 | r.getRightChild().setRootVal('hello') 48 | print(r.getRightChild().getRootVal()) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter6/heapexample1.py: -------------------------------------------------------------------------------- 1 | from pythonds.trees.binheap import BinHeap 2 | 3 | bh = BinHeap() 4 | bh.insert(5) 5 | bh.insert(7) 6 | bh.insert(3) 7 | bh.insert(11) 8 | 9 | print(bh.delMin()) 10 | 11 | print(bh.delMin()) 12 | 13 | print(bh.delMin()) 14 | 15 | print(bh.delMin()) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter6/parsetree.py: -------------------------------------------------------------------------------- 1 | from pythonds.basic.stack import Stack 2 | from pythonds.trees.binaryTree import BinaryTree 3 | 4 | def buildParseTree(fpexp): 5 | fplist = fpexp.split() 6 | pStack = Stack() 7 | eTree = BinaryTree('') 8 | pStack.push(eTree) 9 | currentTree = eTree 10 | for i in fplist: 11 | if i == '(': 12 | currentTree.insertLeft('') 13 | pStack.push(currentTree) 14 | currentTree = currentTree.getLeftChild() 15 | elif i not in ['+', '-', '*', '/', ')']: 16 | currentTree.setRootVal(int(i)) 17 | parent = pStack.pop() 18 | currentTree = parent 19 | elif i in ['+', '-', '*', '/']: 20 | currentTree.setRootVal(i) 21 | currentTree.insertRight('') 22 | pStack.push(currentTree) 23 | currentTree = currentTree.getRightChild() 24 | elif i == ')': 25 | currentTree = pStack.pop() 26 | else: 27 | raise ValueError 28 | return eTree 29 | 30 | pt = buildParseTree("( ( 10 + 5 ) * 3 )") 31 | pt.postorder() 32 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter6/treeexample.py: -------------------------------------------------------------------------------- 1 | from pythonds.trees.binaryTree import BinaryTree 2 | import operator 3 | 4 | x = BinaryTree('*') 5 | x.insertLeft('+') 6 | l = x.getLeftChild() 7 | l.insertLeft(4) 8 | l.insertRight(5) 9 | x.insertRight(7) 10 | 11 | 12 | def printexp(tree): 13 | sVal = "" 14 | if tree: 15 | sVal = '(' + printexp(tree.getLeftChild()) 16 | sVal = sVal + str(tree.getRootVal()) 17 | sVal = sVal + printexp(tree.getRightChild())+')' 18 | return sVal 19 | 20 | def postordereval(tree): 21 | opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} 22 | res1 = None 23 | res2 = None 24 | if tree: 25 | res1 = postordereval(tree.getLeftChild()) 26 | res2 = postordereval(tree.getRightChild()) 27 | if res1 and res2: 28 | return opers[tree.getRootVal()](res1,res2) 29 | else: 30 | return tree.getRootVal() 31 | 32 | print(printexp(x)) 33 | 34 | print(postordereval(x)) 35 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter7/wordladder.py: -------------------------------------------------------------------------------- 1 | from pythonds.graphs import Graph, Vertex 2 | from pythonds.basic import Queue 3 | 4 | def buildGraph(wordFile): 5 | d = {} 6 | g = Graph() 7 | wfile = open(wordFile,'r') 8 | # create buckets of words that differ by one letter 9 | for line in wfile: 10 | word = line[:-1] 11 | for i in range(len(word)): 12 | bucket = word[:i] + '_' + word[i+1:] 13 | if bucket in d: 14 | d[bucket].append(word) 15 | else: 16 | d[bucket] = [word] 17 | # add vertices and edges for words in the same bucket 18 | for bucket in d.keys(): 19 | for word1 in d[bucket]: 20 | for word2 in d[bucket]: 21 | if word1 != word2: 22 | g.addEdge(word1,word2) 23 | return g 24 | 25 | 26 | def bfs(g,start): 27 | start.setDistance(0) 28 | start.setPred(None) 29 | vertQueue = Queue() 30 | vertQueue.enqueue(start) 31 | while (vertQueue.size() > 0): 32 | currentVert = vertQueue.dequeue() 33 | for nbr in currentVert.getConnections(): 34 | if (nbr.getColor() == 'white'): 35 | nbr.setColor('gray') 36 | nbr.setDistance(currentVert.getDistance() + 1) 37 | nbr.setPred(currentVert) 38 | vertQueue.enqueue(nbr) 39 | currentVert.setColor('black') 40 | 41 | 42 | def traverse(y): 43 | x = y 44 | while (x.getPred()): 45 | print(x.getId()) 46 | x = x.getPred() 47 | print(x.getId()) 48 | 49 | 50 | wordgraph = buildGraph("fourletterwords.txt") 51 | 52 | bfs(wordgraph, wordgraph.getVertex('FOOL')) 53 | 54 | traverse(wordgraph.getVertex('SAGE')) 55 | 56 | #traverse(wordgraph.getVertex('COOL')) -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/Chapter7/wordproc.py: -------------------------------------------------------------------------------- 1 | f = open("rawwords.txt","r") 2 | wl = [] 3 | for aline in f: 4 | l = aline.split() 5 | wl.append(l[0]) 6 | 7 | 8 | of = open("fourletterwords.txt","w") 9 | 10 | for w in wl: 11 | of.write(w+'\n') 12 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/__init__.py -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/__pycache__/__init__.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | #__all__ = ["stack"] 3 | 4 | 5 | from .stack import Stack 6 | from .queue import Queue 7 | 8 | 9 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/__init__.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/queue.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/queue.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/stack.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/basic/__pycache__/stack.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/deque.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #deque.py 6 | 7 | 8 | class Deque: 9 | def __init__(self): 10 | self.items = [] 11 | 12 | def isEmpty(self): 13 | return self.items == [] 14 | 15 | def addFront(self, item): 16 | self.items.append(item) 17 | 18 | def addRear(self, item): 19 | self.items.insert(0,item) 20 | 21 | def removeFront(self): 22 | return self.items.pop() 23 | 24 | def removeRear(self): 25 | return self.items.pop(0) 26 | 27 | def size(self): 28 | return len(self.items) 29 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/queue.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #queue.py 6 | 7 | class Queue: 8 | def __init__(self): 9 | self.items = [] 10 | 11 | def isEmpty(self): 12 | return self.items == [] 13 | 14 | def enqueue(self, item): 15 | self.items.insert(0,item) 16 | 17 | def dequeue(self): 18 | return self.items.pop() 19 | 20 | def size(self): 21 | return len(self.items) 22 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/basic/stack.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #stack.py 6 | 7 | class Stack: 8 | def __init__(self): 9 | self.items = [] 10 | 11 | def isEmpty(self): 12 | return self.items == [] 13 | 14 | def push(self, item): 15 | self.items.append(item) 16 | 17 | def pop(self): 18 | return self.items.pop() 19 | 20 | def peek(self): 21 | return self.items[len(self.items)-1] 22 | 23 | def size(self): 24 | return len(self.items) 25 | 26 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/graphs/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from .adjGraph import Graph 4 | from .adjGraph import Vertex 5 | from .priorityQueue import PriorityQueue 6 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/graphs/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- 1 | l 2 | &CMc@s4ddlmZddlmZddlmZdS(i(uGraph(uVertex(u PriorityQueueN(uadjGraphuGraphuVertexu priorityQueueu PriorityQueue(((upythonds/graphs/__init__.pyus -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/graphs/__pycache__/adjGraph.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/graphs/__pycache__/adjGraph.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/graphs/__pycache__/priorityQueue.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/graphs/__pycache__/priorityQueue.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | from .balance import AVLTree 5 | from .bst import BinarySearchTree 6 | from .binheap import BinHeap 7 | 8 | 9 | -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- 1 | l 2 | |%CMc@s4ddlmZddlmZddlmZdS(i(uAVLTree(uBinarySearchTree(uBinHeapN(ubalanceuAVLTreeubstuBinarySearchTreeubinheapuBinHeap(((upythonds/trees/__init__.pyus -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/balance.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/balance.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/binheap.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/binheap.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/bst.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/trees/__pycache__/bst.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/PythonDSExamplePrograms/pythonds/trees/bst.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/PythonDSExamplePrograms/pythonds/trees/bst.pyc -------------------------------------------------------------------------------- /pythonds/ReadMe.txt: -------------------------------------------------------------------------------- 1 | 2 | For more informaton on Problem Solving with Algorithms and Data Structures Using Python, 3 | See pythonworks.org webpage: 4 | 5 | http://www.pythonworks.org/pythonds -------------------------------------------------------------------------------- /pythonds/pythonds.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds.zip -------------------------------------------------------------------------------- /pythonds/pythonds/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/__init__.py -------------------------------------------------------------------------------- /pythonds/pythonds/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/__pycache__/__init__.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/basic/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | #__all__ = ["stack"] 3 | 4 | 5 | from .stack import Stack 6 | from .queue import Queue 7 | from .deque import Deque 8 | 9 | 10 | -------------------------------------------------------------------------------- /pythonds/pythonds/basic/deque.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #deque.py 6 | 7 | 8 | class Deque: 9 | def __init__(self): 10 | self.items = [] 11 | 12 | def isEmpty(self): 13 | return self.items == [] 14 | 15 | def addFront(self, item): 16 | self.items.append(item) 17 | 18 | def addRear(self, item): 19 | self.items.insert(0,item) 20 | 21 | def removeFront(self): 22 | return self.items.pop() 23 | 24 | def removeRear(self): 25 | return self.items.pop(0) 26 | 27 | def size(self): 28 | return len(self.items) 29 | -------------------------------------------------------------------------------- /pythonds/pythonds/basic/queue.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #queue.py 6 | 7 | class Queue: 8 | def __init__(self): 9 | self.items = [] 10 | 11 | def isEmpty(self): 12 | return self.items == [] 13 | 14 | def enqueue(self, item): 15 | self.items.insert(0,item) 16 | 17 | def dequeue(self): 18 | return self.items.pop() 19 | 20 | def size(self): 21 | return len(self.items) 22 | -------------------------------------------------------------------------------- /pythonds/pythonds/basic/stack.py: -------------------------------------------------------------------------------- 1 | # Bradley N. Miller, David L. Ranum 2 | # Introduction to Data Structures and Algorithms in Python 3 | # Copyright 2005 4 | # 5 | #stack.py 6 | 7 | class Stack: 8 | def __init__(self): 9 | self.items = [] 10 | 11 | def isEmpty(self): 12 | return self.items == [] 13 | 14 | def push(self, item): 15 | self.items.append(item) 16 | 17 | def pop(self): 18 | return self.items.pop() 19 | 20 | def peek(self): 21 | return self.items[len(self.items)-1] 22 | 23 | def size(self): 24 | return len(self.items) 25 | 26 | -------------------------------------------------------------------------------- /pythonds/pythonds/graphs/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from .adjGraph import Graph 4 | from .adjGraph import Vertex 5 | from .priorityQueue import PriorityQueue 6 | -------------------------------------------------------------------------------- /pythonds/pythonds/graphs/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- 1 | l 2 | &CMc@s4ddlmZddlmZddlmZdS(i(uGraph(uVertex(u PriorityQueueN(uadjGraphuGraphuVertexu priorityQueueu PriorityQueue(((upythonds/graphs/__init__.pyus -------------------------------------------------------------------------------- /pythonds/pythonds/graphs/__pycache__/adjGraph.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/graphs/__pycache__/adjGraph.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/graphs/__pycache__/priorityQueue.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/graphs/__pycache__/priorityQueue.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/trees/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | from .balance import AVLTree 5 | from .bst import BinarySearchTree 6 | from .binheap import BinHeap 7 | 8 | 9 | -------------------------------------------------------------------------------- /pythonds/pythonds/trees/__pycache__/__init__.cpython-32.pyc: -------------------------------------------------------------------------------- 1 | l 2 | |%CMc@s4ddlmZddlmZddlmZdS(i(uAVLTree(uBinarySearchTree(uBinHeapN(ubalanceuAVLTreeubstuBinarySearchTreeubinheapuBinHeap(((upythonds/trees/__init__.pyus -------------------------------------------------------------------------------- /pythonds/pythonds/trees/__pycache__/balance.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/trees/__pycache__/balance.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/trees/__pycache__/binheap.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/trees/__pycache__/binheap.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/trees/__pycache__/bst.cpython-32.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/trees/__pycache__/bst.cpython-32.pyc -------------------------------------------------------------------------------- /pythonds/pythonds/trees/bst.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ErikRHanson/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python/7bca4f6ad95320e97e203b411a5a83a0d42b805c/pythonds/pythonds/trees/bst.pyc --------------------------------------------------------------------------------