From bfc2031ff5279856d6eb76fbd7e2cf905b837dff Mon Sep 17 00:00:00 2001 From: Hemant jain <32552737+Hemant-Jain-Author@users.noreply.github.com> Date: Thu, 29 Mar 2018 20:12:54 +0530 Subject: [PATCH 1/3] Cosmatic change Cosmatic change --- Searching/Searching.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Searching/Searching.py b/Searching/Searching.py index 2be2557..327488a 100755 --- a/Searching/Searching.py +++ b/Searching/Searching.py @@ -42,8 +42,7 @@ def Binarysearch(self, arr, size, value): high = size - 1 while low <= high: - mid = low + (high - low) / 2 - # To avoid the overflow + mid = (low + high) / 2 if arr[mid] == value: return True elif arr[mid] < value: @@ -59,8 +58,7 @@ def BinarySearchRecursive(self, arr, value): def BinarySearchRecursiveUtil(self, arr, low, high, value): if low > high: return False - mid = low + (high - low) / 2 - # To avoid the overflow + mid = (low + high) / 2 if arr[mid] == value: return True elif arr[mid] < value: From e4517c618b3f370f04997068b95989d6e184717f Mon Sep 17 00:00:00 2001 From: Hemant jain <32552737+Hemant-Jain-Author@users.noreply.github.com> Date: Mon, 9 Apr 2018 17:29:39 +0530 Subject: [PATCH 2/3] extra class removal and cleanup extra class removal and cleanup. --- .gitignore | 1 + Algorithms/Fibo.py | 45 +- Algorithms/NQueen.py | 57 +- Algorithms/Prime.py | 56 +- Algorithms/TOH.py | 43 +- BinaryTree/Tree.py | 208 ++-- Collections/Counter.py | 32 +- Collections/Dictionary.py | 41 +- Collections/Heap.py | 31 +- Collections/List.py | 39 +- Collections/Queue.py | 28 +- Collections/Set.py | 28 +- Collections/Stack.py | 37 +- Graph/Graph.py | 470 ++++--- HashTable/HashTableExercise.py | 158 ++- HashTable/HashTableLP.py | 24 +- HashTable/HashTableSC.py | 25 +- Heap/Heap.py | 52 +- Heap/MedianHeap.py | 19 +- IntroductoryChapters/Analysis.py | 317 +++-- IntroductoryChapters/ArrayDemo.py | 30 +- IntroductoryChapters/Bulb.py | 28 +- IntroductoryChapters/Bulb2.py | 26 +- IntroductoryChapters/Bulb3.py | 28 +- IntroductoryChapters/BulbEnum.py | 20 +- IntroductoryChapters/BulbInterface.py | 36 +- IntroductoryChapters/Calculator.py | 11 +- IntroductoryChapters/Circle.py | 3 +- IntroductoryChapters/Circle.pyc | Bin 0 -> 1574 bytes IntroductoryChapters/ForDemo.py | 67 +- IntroductoryChapters/HelloWorld.py | 11 +- IntroductoryChapters/Incriment.py | 59 +- IntroductoryChapters/Introduction.py | 728 +++++------ IntroductoryChapters/LinkedList.py | 7 +- IntroductoryChapters/Rectangle.py | 7 - IntroductoryChapters/Rectangle.pyc | Bin 0 -> 1811 bytes IntroductoryChapters/Shape.py | 6 +- IntroductoryChapters/Shape.pyc | Bin 0 -> 1074 bytes IntroductoryChapters/ShapeDemo.py | 20 +- IntroductoryChapters/Tree.py | 7 +- IntroductoryChapters/minmaxliit.py | 28 +- IntroductoryChapters/type.py | 47 +- LinkedList/CircularLinkedList.py | 37 +- LinkedList/DoublyCircularLinkedList.py | 25 +- LinkedList/DoublyLinkedList.py | 68 +- LinkedList/LinkedList.py | 112 +- Queue/QueueArr.py | 23 +- Queue/QueueList.py | 27 +- Queue/QueueUsingStack.py | 34 +- Searching/Searching.py | 1557 ++++++++++++------------ Sorting/BubbleSort.py | 83 +- Sorting/BucketSort.py | 54 +- Sorting/InsertionSort.py | 45 +- Sorting/MergeSort.py | 88 +- Sorting/QuickSelect.py | 81 +- Sorting/QuickSort.py | 69 +- Sorting/SelectionSort.py | 78 +- Stack/StackArr.py | 20 +- Stack/StackExercise.py | 508 ++++---- Stack/StackList.py | 21 +- Stack/TwoStack.py | 34 +- String/StringTree.py | 43 +- 62 files changed, 2712 insertions(+), 3175 deletions(-) create mode 100644 .gitignore create mode 100644 IntroductoryChapters/Circle.pyc create mode 100644 IntroductoryChapters/Rectangle.pyc create mode 100644 IntroductoryChapters/Shape.pyc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e10e727 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/.metadata/ diff --git a/Algorithms/Fibo.py b/Algorithms/Fibo.py index 0113a56..e1decfc 100755 --- a/Algorithms/Fibo.py +++ b/Algorithms/Fibo.py @@ -1,23 +1,24 @@ -class Prime(object): - @classmethod - def main(cls, args): - print(cls.isPrime(50)) - print(cls.isPrime(47)) - - @classmethod - def isPrime(self, n): - if( n > 1): - answer = True - else: - answer = False - i = 2 - while(i*i <= n): - if(n%i == 0): - answer = False - break - i += 1 - return answer +def fibonacci2(n): + if n <= 1: + return n + return fibonacci(n - 1) + fibonacci(n - 2) -if __name__ == '__main__': - import sys - Prime.main(sys.argv) \ No newline at end of file + +def fibonacci(n): + first = 0 + second = 1 + if (n == 0): + return first; + elif (n == 1): + return second; + i = 2 + while(i <= n): + temp = first + second + first = second + second = temp + i += 1 + return temp + + +print(fibonacci(50)) +print(fibonacci2(50)) diff --git a/Algorithms/NQueen.py b/Algorithms/NQueen.py index c40d386..259ee97 100755 --- a/Algorithms/NQueen.py +++ b/Algorithms/NQueen.py @@ -1,41 +1,22 @@ -#!/usr/bin/env python +def Feasible(Q, k): + i = 0 + while i < k: + if Q[k] == Q[i] or abs(Q[i] - Q[k]) == abs(i - k): + return False + i += 1 + return True -class NQueen(object): - @classmethod - def printArr(cls, Q, n): - i = 0 - while i < n: - print(Q[i]) - i += 1 - print("") +def NQueens(Q, k, n): + if k == n: + print (Q) + return + i = 0 + while i < n: + Q[k] = i + if Feasible(Q, k): + NQueens(Q, k + 1, n) + i += 1 - @classmethod - def Feasible(cls, Q, k): - i = 0 - while i < k: - if Q[k] == Q[i] or abs(Q[i] - Q[k]) == abs(i - k): - return False - i += 1 - return True - @classmethod - def NQueens(cls, Q, k, n): - if k == n: - cls.printArr(Q, n) - return - i = 0 - while i < n: - Q[k] = i - if cls.Feasible(Q, k): - cls.NQueens(Q, k + 1, n) - i += 1 - - - @classmethod - def main(cls, args): - Q = [0] * 8 - cls.NQueens(Q, 0, 8) - -if __name__ == '__main__': - import sys - NQueen.main(sys.argv) +Q = [0] * 8 +NQueens(Q, 0, 8) \ No newline at end of file diff --git a/Algorithms/Prime.py b/Algorithms/Prime.py index 226695c..1b176cf 100755 --- a/Algorithms/Prime.py +++ b/Algorithms/Prime.py @@ -1,45 +1,15 @@ -class Fibo(object): - - @classmethod - def main(cls, args): - print(cls.fibonacci(50)) - print(cls.fibonacci2(50)) - - @classmethod - def fibonacci2(cls, n): - if n <= 1: - return n - return cls.fibonacci(n - 1) + cls.fibonacci(n - 2) - - @classmethod - def fibonacci(cls, n): - first = 0 - second = 1 - if (n == 0): - return first; - elif (n == 1): - return second; - i = 2 - while(i <= n): - temp = first + second - first = second - second = temp - i += 1 - return temp - - def isPrime(self, n): - if( n > 1): - answer = True - else: +def isPrime(n): + if(n > 1): + answer = True + else: + answer = False + i = 2 + while(i*i <= n): + if(n % i == 0): answer = False - i = 2 - while(i*i <= n): - if(n%i == 0): - answer = True; - break; - i += 1 - return answer + break + i += 1 + return answer -if __name__ == '__main__': - import sys - Fibo.main(sys.argv) \ No newline at end of file +print(isPrime(50)) +print(isPrime(47)) \ No newline at end of file diff --git a/Algorithms/TOH.py b/Algorithms/TOH.py index ee73f4e..39a60f2 100755 --- a/Algorithms/TOH.py +++ b/Algorithms/TOH.py @@ -1,31 +1,12 @@ -#!/usr/bin/env python -""" generated source for module TOH """ - -class TOH(object): - """ generated source for class TOH """ - - @classmethod - def main(cls, args): - """ generated source for method main """ - - cls.TowersOfHanoi(3) - - @classmethod - def TOHUtil(cls, num, source, dest, temp): - """ generated source for method TOHUtil """ - if num < 1: - return - cls.TOHUtil(num - 1, source, temp, dest) - print("Move disk" , num , "from peg" , source , "to peg" , dest) - cls.TOHUtil(num - 1, temp, dest, source) - - @classmethod - def TowersOfHanoi(cls, num): - """ generated source for method TowersOfHanoi """ - print("The sequence of moves involved in the Tower of Hanoi are :") - cls.TOHUtil(num, 'A', 'C', 'B') - - -if __name__ == '__main__': - import sys - TOH.main(sys.argv) +def TOHUtil(num, source, dest, temp): + if num < 1: + return + TOHUtil(num - 1, source, temp, dest) + print("Move disk" , num , "from peg" , source , "to peg" , dest) + TOHUtil(num - 1, temp, dest, source) + +def TowersOfHanoi(num): + print("The sequence of moves involved in the Tower of Hanoi are :") + TOHUtil(num, 'A', 'C', 'B') + +TowersOfHanoi(3) \ No newline at end of file diff --git a/BinaryTree/Tree.py b/BinaryTree/Tree.py index 587447b..71005a6 100644 --- a/BinaryTree/Tree.py +++ b/BinaryTree/Tree.py @@ -638,110 +638,104 @@ def treeToListRec(self, curr): return Head - @classmethod - def main(cls, args): - #======================================================================= - # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - # t2 = Tree() - # t2.levelOrderBinaryTree(arr) - #======================================================================= - #======================================================================= - # t = Tree() - # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - # # t.levelOrderBinaryTree(arr) - # t.InsertNode(5) - # t.InsertNode(3) - # t.InsertNode(4) - # t.InsertNode(2) - # t.InsertNode(1) - # t.InsertNode(8) - # t.InsertNode(7) - # t.InsertNode(9) - # # print (t.CeilBST(6)) - # t.printAllPath() - # print("") - # t.iterativeInOrder() - # print("") - # t.PrintInOrder() - # print("") - # t.iterativePreOrder() - # print("") - # t.PrintPreOrder() - # print("") - # t.iterativePostOrder() - # print("") - # t.PrintPostOrder() - # print("") - # - # t.PrintBredthFirst() - # # t.treeToList(); - # print ( t.LCA(10, 3) ) - #======================================================================= - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - t2 = Tree() - # t2.levelOrderBinaryTree(arr) - #======================================================================= - # t2.InsertNode(5) - # t2.InsertNode(3) - # t2.InsertNode(4) - # t2.InsertNode(2) - # t2.InsertNode(1) - # t2.InsertNode(8) - # t2.InsertNode(7) - # t2.InsertNode(9) - #======================================================================= - #print t2.Ancestor(1, 10) - #print t2.CeilBST(7) - #print t2.FloorBST(12) - t2.CreateBinaryTree(arr) - t2.PrintInOrder() - print "" - t2.iterativeInOrder() - print "" - t2.PrintPostOrder() - print "" - t2.iterativePostOrder() - print "" - t2.PrintPreOrder() - print "" - t2.iterativePreOrder() - #t2.DeleteNode(8) - #======================================================================= - # t3 = t2.CopyMirrorTree() - # t2.PrintInOrder() - # print "" - # t3.PrintInOrder() - # print t2.Find(18) - # print t2.findMaxBT() - # print t2.FindMax() - # print t2.FindMin() - # t4 = t2.CopyTree() - # t4.PrintInOrder() - # print "" - # t2.PrintInOrder() - # print "" - # t2.PrintPostOrder() - # print "" - # t2.PrintPreOrder() - # print "" - # print t2.numNodes() - # print t2.NthInOrder(2) - # print t2.NthPostOrder(2) - # print t2.NthPreOrder(2) - # print t2.isEqual(t4) - # print t2.TreeDepth() - # print t2.maxLengthPathBT() - # print t2.numFullNodesBT() - # print t2.isBST() - # print t2.isBST2() - # print t2.numLeafNodes() - # print t2.numNodes() - # print t2.printInRange(4, 7) - # print t2.trimOutsideRange(3, 8) - # print t2.PrintInOrder() - #======================================================================= - - -if __name__ == '__main__': - import sys - Tree.main(sys.argv) +#======================================================================= +# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +# t2 = Tree() +# t2.levelOrderBinaryTree(arr) +#======================================================================= +#======================================================================= +# t = Tree() +# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +# # t.levelOrderBinaryTree(arr) +# t.InsertNode(5) +# t.InsertNode(3) +# t.InsertNode(4) +# t.InsertNode(2) +# t.InsertNode(1) +# t.InsertNode(8) +# t.InsertNode(7) +# t.InsertNode(9) +# # print (t.CeilBST(6)) +# t.printAllPath() +# print("") +# t.iterativeInOrder() +# print("") +# t.PrintInOrder() +# print("") +# t.iterativePreOrder() +# print("") +# t.PrintPreOrder() +# print("") +# t.iterativePostOrder() +# print("") +# t.PrintPostOrder() +# print("") +# +# t.PrintBredthFirst() +# # t.treeToList(); +# print ( t.LCA(10, 3) ) +#======================================================================= +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +t2 = Tree() +# t2.levelOrderBinaryTree(arr) +#======================================================================= +# t2.InsertNode(5) +# t2.InsertNode(3) +# t2.InsertNode(4) +# t2.InsertNode(2) +# t2.InsertNode(1) +# t2.InsertNode(8) +# t2.InsertNode(7) +# t2.InsertNode(9) +#======================================================================= +#print t2.Ancestor(1, 10) +#print t2.CeilBST(7) +#print t2.FloorBST(12) +t2.CreateBinaryTree(arr) +t2.PrintInOrder() +print "" +t2.iterativeInOrder() +print "" +t2.PrintPostOrder() +print "" +t2.iterativePostOrder() +print "" +t2.PrintPreOrder() +print "" +t2.iterativePreOrder() +#t2.DeleteNode(8) +#======================================================================= +# t3 = t2.CopyMirrorTree() +# t2.PrintInOrder() +# print "" +# t3.PrintInOrder() +# print t2.Find(18) +# print t2.findMaxBT() +# print t2.FindMax() +# print t2.FindMin() +# t4 = t2.CopyTree() +# t4.PrintInOrder() +# print "" +# t2.PrintInOrder() +# print "" +# t2.PrintPostOrder() +# print "" +# t2.PrintPreOrder() +# print "" +# print t2.numNodes() +# print t2.NthInOrder(2) +# print t2.NthPostOrder(2) +# print t2.NthPreOrder(2) +# print t2.isEqual(t4) +# print t2.TreeDepth() +# print t2.maxLengthPathBT() +# print t2.numFullNodesBT() +# print t2.isBST() +# print t2.isBST2() +# print t2.numLeafNodes() +# print t2.numNodes() +# print t2.printInRange(4, 7) +# print t2.trimOutsideRange(3, 8) +# print t2.PrintInOrder() +#======================================================================= + diff --git a/Collections/Counter.py b/Collections/Counter.py index 33221bc..fba76e6 100755 --- a/Collections/Counter.py +++ b/Collections/Counter.py @@ -1,23 +1,13 @@ from collections import Counter -class MyClass: - - @classmethod - def main(cls, args): - """ generated source for method main """ - seq = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] - mycounter = Counter(seq) - print mycounter - print mycounter.get(3) - print mycounter.has_key(3) - mycounter.pop(4) - print mycounter - print 4 in mycounter - mycounter[5] += 1 - mycounter[5] += 1 - print mycounter - - -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) +seq = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] +mycounter = Counter(seq) +print mycounter +print mycounter.get(3) +print mycounter.has_key(3) +mycounter.pop(4) +print mycounter +print 4 in mycounter +mycounter[5] += 1 +mycounter[5] += 1 +print mycounter diff --git a/Collections/Dictionary.py b/Collections/Dictionary.py index 4ae3eb3..02b7241 100755 --- a/Collections/Dictionary.py +++ b/Collections/Dictionary.py @@ -1,28 +1,19 @@ from collections import OrderedDict -class MyClass: - @classmethod - def main(cls, args): - """ generated source for method main """ - a = {} - a["apple"] = 40 - a["banana"] = 10 - a["mango"] = 20 - print a - print a["mango"] - print a.get("mango") - print "apple" in a - - b = OrderedDict() - b["apple"] = 40 - b["banana"] = 10 - b["mango"] = 20 - print b - print b["mango"] - print b.get("mango") - print "banana" in b - +a = {} +a["apple"] = 40 +a["banana"] = 10 +a["mango"] = 20 +print a +print a["mango"] +print a.get("mango") +print "apple" in a -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) +b = OrderedDict() +b["apple"] = 40 +b["banana"] = 10 +b["mango"] = 20 +print b +print b["mango"] +print b.get("mango") +print "banana" in b \ No newline at end of file diff --git a/Collections/Heap.py b/Collections/Heap.py index 7d6a6c5..bda6ac8 100755 --- a/Collections/Heap.py +++ b/Collections/Heap.py @@ -1,22 +1,15 @@ import heapq -class MyClass: - @classmethod - def main(cls, args): - """ generated source for method main """ - myheap = [19,1,18] # creates heap from list. - heapq.heapify(myheap) - print myheap - heapq.heappush(myheap, 5) # pushes a new item on the heap - heapq.heappush(myheap, 3) - heapq.heappush(myheap, 8) - heapq.heappush(myheap, 2) - print myheap - print heapq.heappop(myheap) # pops the smallest item from the heap - print myheap - print myheap[0] # peek the smallest element of the heap. - print len(myheap) +myheap = [19,1,18] # creates heap from list. +heapq.heapify(myheap) +print myheap +heapq.heappush(myheap, 5) # pushes a new item on the heap +heapq.heappush(myheap, 3) +heapq.heappush(myheap, 8) +heapq.heappush(myheap, 2) +print myheap +print heapq.heappop(myheap) # pops the smallest item from the heap +print myheap +print myheap[0] # peek the smallest element of the heap. +print len(myheap) -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) diff --git a/Collections/List.py b/Collections/List.py index 180406a..947d309 100755 --- a/Collections/List.py +++ b/Collections/List.py @@ -1,24 +1,15 @@ -class MyClass: - @classmethod - def main(cls, args): - """ generated source for method main """ - a = [] - a.append(5) - a.append(4) - a.append(2) - a.append(40) - print a - print a + a - print len(a) - a.remove(4) - print a - print a.pop() - a.sort() - print a - a.reverse() - print a - - -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) \ No newline at end of file +a = [] +a.append(5) +a.append(4) +a.append(2) +a.append(40) +print a +print a + a +print len(a) +a.remove(4) +print a +print a.pop() +a.sort() +print a +a.reverse() +print a diff --git a/Collections/Queue.py b/Collections/Queue.py index 6372157..8821059 100755 --- a/Collections/Queue.py +++ b/Collections/Queue.py @@ -1,20 +1,12 @@ from collections import deque -class MyClass: - @classmethod - def main(cls, args): - """ generated source for method main """ - a = deque([]) - a.append(5) - a.append(4) - a.append(3) - a.append(2) - a.append(1) - a.append(0) - print a - print a.popleft() - print a - -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) \ No newline at end of file +a = deque([]) +a.append(5) +a.append(4) +a.append(3) +a.append(2) +a.append(1) +a.append(0) +print a +print a.popleft() +print a diff --git a/Collections/Set.py b/Collections/Set.py index c589cea..d96ae60 100755 --- a/Collections/Set.py +++ b/Collections/Set.py @@ -1,18 +1,10 @@ -class MyClass: - @classmethod - def main(cls, args): - """ generated source for method main """ - a = set() - a.add(5) - a.add(4) - a.add(2) - a.add(1) - a.add(5) - print a - print (4 in a) - a.remove(4) - print a - -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) \ No newline at end of file +a = set() +a.add(5) +a.add(4) +a.add(2) +a.add(1) +a.add(5) +print a +print (4 in a) +a.remove(4) +print a diff --git a/Collections/Stack.py b/Collections/Stack.py index 18a04df..d8fef62 100755 --- a/Collections/Stack.py +++ b/Collections/Stack.py @@ -1,25 +1,16 @@ from collections import Set -class MyClass: - - @classmethod - def main(cls, args): - """ generated source for method main """ - a = set() - a.add(5) - a.add(5) - a.add(4) - a.add(2) - a.add(5) - print a - print len(a) - a.remove(4) - print a - a.add(8) - print a.pop() - print a - print (5 in a) - -if __name__ == '__main__': - import sys - MyClass.main(sys.argv) \ No newline at end of file +a = set() +a.add(5) +a.add(5) +a.add(4) +a.add(2) +a.add(5) +print a +print len(a) +a.remove(4) +print a +a.add(8) +print a.pop() +print a +print (5 in a) diff --git a/Graph/Graph.py b/Graph/Graph.py index 7f4e7a8..b20238b 100755 --- a/Graph/Graph.py +++ b/Graph/Graph.py @@ -1,5 +1,6 @@ #!/usr/bin/env python import heapq +import sys from collections import deque class Graph(object): @@ -46,266 +47,249 @@ def Print(self): print "" i += 1 - @classmethod - def Dijkstra(cls, gph, source): - previous = [-1] * gph.count - dist = [sys.maxint] * gph.count +def Dijkstra(gph, source): + previous = [-1] * gph.count + dist = [sys.maxint] * gph.count - dist[source] = 0 - previous[source] = -1 + dist[source] = 0 + previous[source] = -1 - pqarray = [] - node = cls.AdjNode(source, source, 0) - heapq.heappush(pqarray, (0, node)) + pqarray = [] + node = Graph.AdjNode(source, source, 0) + heapq.heappush(pqarray, (0, node)) + + while len(pqarray) != 0: + val = heapq.heappop(pqarray) + node = val[1] - while len(pqarray) != 0: - val = heapq.heappop(pqarray) - node = val[1] - - adl = gph.array[node.destination] - adn = adl.head - - while adn != None: - alt = adn.cost + dist[adn.source] - if alt < dist[adn.destination]: - dist[adn.destination] = alt - previous[adn.destination] = adn.source - node = cls.AdjNode(adn.source, adn.destination, alt) - heapq.heappush(pqarray, (alt, node)) - adn = adn.next - count = gph.count - i = 0 - while i < count: - if dist[i] == sys.maxint: - print "node id" , i , "prev" , previous[i] , "distance : Unreachable" - else: - print "node id" , i , "prev" , previous[i] , "distance :" , dist[i] - i += 1 - - @classmethod - def Prims(cls, gph): - previous = [-1] * gph.count - dist = [sys.maxint] * gph.count - source = 1 - dist[source] = 0 - previous[source] = -1 + adl = gph.array[node.destination] + adn = adl.head + + while adn != None: + alt = adn.cost + dist[adn.source] + if alt < dist[adn.destination]: + dist[adn.destination] = alt + previous[adn.destination] = adn.source + node = Graph.AdjNode(adn.source, adn.destination, alt) + heapq.heappush(pqarray, (alt, node)) + adn = adn.next + count = gph.count + i = 0 + while i < count: + if dist[i] == sys.maxint: + print "node id" , i , "prev" , previous[i] , "distance : Unreachable" + else: + print "node id" , i , "prev" , previous[i] , "distance :" , dist[i] + i += 1 + +def Prims(gph): + previous = [-1] * gph.count + dist = [sys.maxint] * gph.count + source = 1 + dist[source] = 0 + previous[source] = -1 - pqarray = [] - node = cls.AdjNode(source, source, 0) - heapq.heappush(pqarray, (0, node)) + pqarray = [] + node = Graph.AdjNode(source, source, 0) + heapq.heappush(pqarray, (0, node)) + + while len(pqarray) != 0: + val = heapq.heappop(pqarray) + node = val[1] - while len(pqarray) != 0: - val = heapq.heappop(pqarray) - node = val[1] - - if dist[node.destination] < node.cost: - continue - - dist[node.destination] = node.cost; - previous[node.destination] = node.source; - - adl = gph.array[node.destination] - adn = adl.head - - while adn != None: - if previous[adn.destination]==-1: - node = cls.AdjNode(adn.source, adn.destination, adn.cost) - heapq.heappush(pqarray, (adn.cost, node)) - adn = adn.next - count = gph.count - i = 0 - while i < count: - if dist[i] == sys.maxint: - print "node id" , i , "prev" , previous[i] , "distance : Unreachable" - else: - print "node id" , i , "prev" , previous[i] , "distance :" , dist[i] - i += 1 - - - @classmethod - def TopologicalSortDFS(cls, gph, index, visited, stk): - head = gph.array[index].head + if dist[node.destination] < node.cost: + continue + + dist[node.destination] = node.cost; + previous[node.destination] = node.source; + + adl = gph.array[node.destination] + adn = adl.head + + while adn != None: + if previous[adn.destination]==-1: + node = Graph.AdjNode(adn.source, adn.destination, adn.cost) + heapq.heappush(pqarray, (adn.cost, node)) + adn = adn.next + count = gph.count + i = 0 + while i < count: + if dist[i] == sys.maxint: + print "node id" , i , "prev" , previous[i] , "distance : Unreachable" + else: + print "node id" , i , "prev" , previous[i] , "distance :" , dist[i] + i += 1 + + +def TopologicalSortDFS(gph, index, visited, stk): + head = gph.array[index].head + while head != None: + if visited[head.destination] == 0: + visited[head.destination] = 1 + TopologicalSortDFS(gph, head.destination, visited, stk) + head = head.next + stk.append(index) + +def TopologicalSort(gph): + stk = [] + count = gph.count + visited = [0] * count + i = 0 + while i < count: + if visited[i] == 0: + visited[i] = 1 + TopologicalSortDFS(gph, i, visited, stk) + i += 1 + while len(stk) != 0: + print stk.pop(), + +def PathExist(gph, source, destination): + count = gph.count + visited = [False] * count + visited[source] = True + DFSRec(gph, source, visited) + return visited[destination] + +def DFSRec(gph, index, visited): + head = gph.array[index].head + while head != None: + if visited[head.destination] == False: + visited[head.destination] = True + DFSRec(gph, head.destination, visited) + head = head.next + +def isConnected(gph): + count = gph.count + visited = [False] * count + visited[0] = True + DFSRec(gph, 0, visited) + i = 0 + while i < count: + if visited[i] == False: + return False + i += 1 + return True + +def DFSStack(gph): + count = gph.count + visited = [0] * count + stk = [] + visited[0] = 1 + stk.append(object) + while len(stk) != 0: + curr = stk.pop() + head = gph.array[curr].head while head != None: if visited[head.destination] == 0: visited[head.destination] = 1 - cls.TopologicalSortDFS(gph, head.destination, visited, stk) + append(head.destination) head = head.next - stk.append(index) - @classmethod - def TopologicalSort(cls, gph): - stk = [] - count = gph.count - visited = [0] * count - i = 0 - while i < count: - if visited[i] == 0: - visited[i] = 1 - cls.TopologicalSortDFS(gph, i, visited, stk) - i += 1 - while len(stk) != 0: - print stk.pop(), +def DFS(gph): + count = gph.count + visited = [0] * count + i = 0 + while i < count: + if visited[i] == 0: + visited[i] = 1 + DFSRec(gph, i, visited) + i += 1 - @classmethod - def PathExist(cls, gph, source, destination): - count = gph.count - visited = [False] * count - visited[source] = True - cls.DFSRec(gph, source, visited) - return visited[destination] - - @classmethod - def DFSRec(cls, gph, index, visited): - head = gph.array[index].head +def BFSQueue(gph, index, visited): + que = deque([]) + visited[index] = 1 + que.append(index) + while len(que) != 0: + curr = que.popleft() + head = gph.array[curr].head while head != None: - if visited[head.destination] == False: - visited[head.destination] = True - cls.DFSRec(gph, head.destination, visited) + if visited[head.destination] == 0: + visited[head.destination] = 1 + que.append(head.destination) head = head.next - - @classmethod - def isConnected(cls, gph): - count = gph.count - visited = [False] * count - visited[0] = True - cls.DFSRec(gph, 0, visited) - i = 0 - while i < count: - if visited[i] == False: - return False - i += 1 - return True - - @classmethod - def DFSStack(cls, gph): - count = gph.count - visited = [0] * count - stk = [] - visited[0] = 1 - stk.append(object) - while len(stk) != 0: - curr = stk.pop() - head = gph.array[curr].head - while head != None: - if visited[head.destination] == 0: - visited[head.destination] = 1 - cls.append(head.destination) - head = head.next - @classmethod - def DFS(cls, gph): - count = gph.count - visited = [0] * count - i = 0 - while i < count: - if visited[i] == 0: - visited[i] = 1 - cls.DFSRec(gph, i, visited) - i += 1 - - @classmethod - def BFSQueue(cls, gph, index, visited): - que = deque([]) - visited[index] = 1 - que.append(index) - while len(que) != 0: - curr = que.popleft() - head = gph.array[curr].head - while head != None: - if visited[head.destination] == 0: - visited[head.destination] = 1 - que.append(head.destination) - head = head.next - - @classmethod - def BFS(cls, gph): - count = gph.count - visited = [0] * count - i = 0 - while i < count: - if visited[i] == 0: - cls.BFSQueue(gph, i, visited) - i += 1 +def BFS(gph): + count = gph.count + visited = [0] * count + i = 0 + while i < count: + if visited[i] == 0: + BFSQueue(gph, i, visited) + i += 1 - @classmethod - def ShortestPath(cls, gph, source): - count = gph.count - distance = [-1] * count - path = [-1] * count - que = deque([]) +def ShortestPath(gph, source): + count = gph.count + distance = [-1] * count + path = [-1] * count + que = deque([]) + + que.append(source) + distance[source] = 0 + while len(que) != 0: + curr = que.popleft() + head = gph.array[curr].head + while head != None: + if distance[head.destination] == -1: + distance[head.destination] = distance[curr] + 1 + path[head.destination] = curr + que.append(head.destination) + head = head.next + i = 0 + while i < count: + print path[i] , "to" , i , "weight" , distance[i] + i += 1 - que.append(source) - distance[source] = 0 - while len(que) != 0: - curr = que.popleft() - head = gph.array[curr].head +def BellmanFordShortestPath(gph, source): + count = gph.count + distance = [sys.maxint] * count + path = [-1] * count + + distance[source] = 0 + i = 0 + while i < count - 1: + j = 0 + while j < count: + head = gph.array[j].head while head != None: - if distance[head.destination] == -1: - distance[head.destination] = distance[curr] + 1 - path[head.destination] = curr - que.append(head.destination) + newDistance = distance[j] + head.cost + if distance[head.destination] > newDistance: + distance[head.destination] = newDistance + path[head.destination] = j head = head.next - i = 0 - while i < count: - print path[i] , "to" , i , "weight" , distance[i] - i += 1 - - @classmethod - def BellmanFordShortestPath(cls, gph, source): - count = gph.count - distance = [sys.maxint] * count - path = [-1] * count - - distance[source] = 0 - i = 0 - while i < count - 1: - j = 0 - while j < count: - head = gph.array[j].head - while head != None: - newDistance = distance[j] + head.cost - if distance[head.destination] > newDistance: - distance[head.destination] = newDistance - path[head.destination] = j - head = head.next - j += 1 - i += 1 - - i = 0 - while i < count: - print path[i] , "to" , i , "weight" , distance[i] - i += 1 + j += 1 + i += 1 + + i = 0 + while i < count: + print path[i] , "to" , i , "weight" , distance[i] + i += 1 - @classmethod - def main(cls, args): - gph = Graph(9) - gph.AddBiEdge(0, 2, 1) - gph.AddBiEdge(1, 2, 5) - gph.AddBiEdge(1, 3, 7) - gph.AddBiEdge(1, 4, 9) - gph.AddBiEdge(3, 2, 2) - gph.AddBiEdge(3, 5, 4) - gph.AddBiEdge(4, 5, 6) - gph.AddBiEdge(4, 6, 3) - gph.AddBiEdge(5, 7, 1) - gph.AddBiEdge(6, 7, 7) - gph.AddBiEdge(7, 8, 17) - cls.Dijkstra(gph, 1) - # cls.Prims(gph) - """print cls.PathExist(gph, 1, 5) - print cls.isConnected(gph) - cls.ShortestPath(gph, 1) - cls.BellmanFordShortestPath(gph, 1) - g = Graph(6); - g.AddEdge(5, 2); - g.AddEdge(5, 0); - g.AddEdge(4, 0); - g.AddEdge(4, 1); - g.AddEdge(2, 3); - g.AddEdge(3, 1); - print "Topological Sort::", - Graph.TopologicalSort(g);""" -if __name__ == '__main__': - import sys - Graph.main(sys.argv) +gph = Graph(9) +gph.AddBiEdge(0, 2, 1) +gph.AddBiEdge(1, 2, 5) +gph.AddBiEdge(1, 3, 7) +gph.AddBiEdge(1, 4, 9) +gph.AddBiEdge(3, 2, 2) +gph.AddBiEdge(3, 5, 4) +gph.AddBiEdge(4, 5, 6) +gph.AddBiEdge(4, 6, 3) +gph.AddBiEdge(5, 7, 1) +gph.AddBiEdge(6, 7, 7) +gph.AddBiEdge(7, 8, 17) +Dijkstra(gph, 1) +# Prims(gph) +"""print PathExist(gph, 1, 5) +print isConnected(gph) +ShortestPath(gph, 1) +BellmanFordShortestPath(gph, 1) +g = Graph(6); +g.AddEdge(5, 2); +g.AddEdge(5, 0); +g.AddEdge(4, 0); +g.AddEdge(4, 1); +g.AddEdge(2, 3); +g.AddEdge(3, 1); +print "Topological Sort::", +Graph.TopologicalSort(g);""" + diff --git a/HashTable/HashTableExercise.py b/HashTable/HashTableExercise.py index 6f27cd9..1806181 100755 --- a/HashTable/HashTableExercise.py +++ b/HashTable/HashTableExercise.py @@ -1,95 +1,85 @@ #!/usr/bin/env python from collections import Counter -class HashTableExercise(object): - @classmethod - def main(cls, args): - first = "hello" - second = "elloh" - third = "world" - print "isAnagram : " , cls.isAnagram(first, second) - print "isAnagram : " , cls.isAnagram(first, third) - print cls.removeDuplicate(first) - print first - arr = [1, 2, 3, 5, 6, 7, 8, 9, 10] - print cls.findMissing(arr, 1, 10) - arr1 = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1] - cls.printRepeating(arr1) - cls.printFirstRepeating(arr1) - - @classmethod - def isAnagram(cls, str1, str2): - size1 = len(str1) - size2 = len(str2) - if size1 != size2: +def isAnagram(str1, str2): + size1 = len(str1) + size2 = len(str2) + if size1 != size2: + return False + cm = Counter() + for ch in str1: + cm[ch] += 1 + for ch in str2: + if cm[ch] == 0: return False - cm = Counter() - for ch in str1: - cm[ch] += 1 - for ch in str2: - if cm[ch] == 0: - return False - else: - cm[ch] -= 1 - return True + else: + cm[ch] -= 1 + return True + +def removeDuplicate(exp): + hs = set() + retexp = "" + for ch in exp: + if (ch in hs) == False: + retexp += ch + hs.add(ch) + return retexp + +def findMissing(arr, start, end): + hs = set() + for i in arr: + hs.add(i) + curr = start + while curr <= end: + if (curr in hs) == False: + return curr + curr += 1 + return sys.maxint - @classmethod - def removeDuplicate(cls, exp): - hs = set() - retexp = "" - for ch in exp: - if (ch in hs) == False: - retexp += ch - hs.add(ch) - return retexp +def printRepeating(arr): + hs = set() + print "Repeating elements are:", + for val in arr: + if val in hs: + print val, + else: + hs.add(val) - @classmethod - def findMissing(cls, arr, start, end): - hs = set() - for i in arr: - hs.add(i) - curr = start - while curr <= end: - if (curr in hs) == False: - return curr - curr += 1 - return sys.maxint +def printFirstRepeating(arr): + size = len(arr) + i = 0 + hs = Counter() + while i < size: + hs[arr[i]] += 1 + i += 1 + i = 0 + while i < size: + if hs.get(arr[i]) > 1: + print "First Repeating number is : " , arr[i] + return arr[i] + i += 1 - @classmethod - def printRepeating(cls, arr): - hs = set() - print "Repeating elements are:", - for val in arr: - if val in hs: - print val, - else: - hs.add(val) +def hornerHash(self, key, tableSize): + size = len(key) + h = 0 + i = 0 + while i < size: + h = (32 * h + key[i]) % tableSize + i += 1 + return h - @classmethod - def printFirstRepeating(cls, arr): - size = len(arr) - i = 0 - hs = Counter() - while i < size: - hs[arr[i]] += 1 - i += 1 - i = 0 - while i < size: - if hs.get(arr[i]) > 1: - print "First Repeating number is : " , arr[i] - return arr[i] - i += 1 +first = "hello" +second = "elloh" +third = "world" +print "isAnagram : " , isAnagram(first, second) +print "isAnagram : " , isAnagram(first, third) +print removeDuplicate(first) +print first +arr = [1, 2, 3, 5, 6, 7, 8, 9, 10] +print findMissing(arr, 1, 10) +arr1 = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1] +printRepeating(arr1) +printFirstRepeating(arr1) - def hornerHash(self, key, tableSize): - size = len(key) - h = 0 - i = 0 - while i < size: - h = (32 * h + key[i]) % tableSize - i += 1 - return h -if __name__ == '__main__': - import sys - HashTableExercise.main(sys.argv) diff --git a/HashTable/HashTableLP.py b/HashTable/HashTableLP.py index 3e7c467..c4d85c9 100755 --- a/HashTable/HashTableLP.py +++ b/HashTable/HashTableLP.py @@ -66,20 +66,14 @@ def Print(self): print "Node at index [" , i , " ] :: " , self.Arr[i] i += 1 -class HashTableDemo: - @classmethod - def main(cls, args): - ht = HashTable(1000) - ht.InsertNode(89) - ht.InsertNode(18) - ht.InsertNode(49) - ht.Print() - ht.DeleteNode(89) - ht.DeleteNode(18) - ht.DeleteNode(49) - ht.Print() +ht = HashTable(1000) +ht.InsertNode(89) +ht.InsertNode(18) +ht.InsertNode(49) +ht.Print() +ht.DeleteNode(89) +ht.DeleteNode(18) +ht.DeleteNode(49) +ht.Print() -if __name__ == '__main__': - import sys - HashTableDemo.main(sys.argv) diff --git a/HashTable/HashTableSC.py b/HashTable/HashTableSC.py index deb356a..167d8b8 100755 --- a/HashTable/HashTableSC.py +++ b/HashTable/HashTableSC.py @@ -60,20 +60,13 @@ def find(self, value): head = head.next return False -class HashTableDemo: - @classmethod - def main(cls, args): - ht = HashTableSC() - i = 100 - while i < 110: - ht.insert(i) - i += 1 - print "search 100 :: " , ht.find(100) - print "remove 100 :: " , ht.delete(100) - print "search 100 :: " , ht.find(100) - print "remove 100 :: " , ht.delete(100) - -if __name__ == '__main__': - import sys - HashTableDemo.main(sys.argv) \ No newline at end of file +ht = HashTableSC() +i = 100 +while i < 110: + ht.insert(i) + i += 1 +print "search 100 :: " , ht.find(100) +print "remove 100 :: " , ht.delete(100) +print "search 100 :: " , ht.find(100) +print "remove 100 :: " , ht.delete(100) diff --git a/Heap/Heap.py b/Heap/Heap.py index fc3effa..5a1d893 100755 --- a/Heap/Heap.py +++ b/Heap/Heap.py @@ -62,30 +62,6 @@ def peek(self): raise RuntimeError("Heap is empty.") return self.arr[1] - @classmethod - def heapSort(cls, array): - hp = Heap(array) - i = 0 - while i < len(array): - array[i] = hp.remove() - i += 1 - - @classmethod - def main(cls, args): - a = [1, 9, 6, 7, 8, 0, 2, 4, 5, 3] - hp = Heap(a) - hp.printHeap() - b = hp.arr[1:] - print hp.IsMinHeap(b) - print hp.IsMinHeap(a) - i = 0 - while i < len(a): - print hp.remove(), - i += 1 - print "" - Heap.heapSort(a) - print a, - def IsMinHeap(self, arr): size = len(arr) i = 0 @@ -113,8 +89,26 @@ def IsMaxHeap(self, arr): return False i += 1 return True - - -if __name__ == '__main__': - import sys - Heap.main(sys.argv) + + + +def heapSort(array): + hp = Heap(array) + i = 0 + while i < len(array): + array[i] = hp.remove() + i += 1 + +a = [1, 9, 6, 7, 8, 0, 2, 4, 5, 3] +hp = Heap(a) +hp.printHeap() +b = hp.arr[1:] +print hp.IsMinHeap(b) +print hp.IsMinHeap(a) +i = 0 +while i < len(a): + print hp.remove(), + i += 1 +print "" +heapSort(a) +print a, diff --git a/Heap/MedianHeap.py b/Heap/MedianHeap.py index bd8a20f..70fafec 100755 --- a/Heap/MedianHeap.py +++ b/Heap/MedianHeap.py @@ -49,16 +49,11 @@ def getMedian(self): return self.MinHeapPeek() - @classmethod - def main(cls, args): - arr = [1, 9, 2, 8, 3, 7, 4, 6, 5, 1, 9, 2, 8, 3, 7, 4, 6, 5, 10, 10] - hp = MedianHeap() - i = 0 - while i < 20: - hp.insert(arr[i]) - print "Median after insertion of " , arr[i] , " is " , hp.getMedian() - i += 1 -if __name__ == '__main__': - import sys - MedianHeap.main(sys.argv) \ No newline at end of file +arr = [1, 9, 2, 8, 3, 7, 4, 6, 5, 1, 9, 2, 8, 3, 7, 4, 6, 5, 10, 10] +hp = MedianHeap() +i = 0 +while i < 20: + hp.insert(arr[i]) + print "Median after insertion of " , arr[i] , " is " , hp.getMedian() + i += 1 diff --git a/IntroductoryChapters/Analysis.py b/IntroductoryChapters/Analysis.py index 25a14d0..d9a9da4 100755 --- a/IntroductoryChapters/Analysis.py +++ b/IntroductoryChapters/Analysis.py @@ -2,173 +2,164 @@ import math -class Analysis(object): - - def fun1(self, n): - m = 0 - i = 0 - while i < n: +def fun1(n): + m = 0 + i = 0 + while i < n: + m += 1 + i += 1 + return m + +def fun2(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < n: m += 1 - i += 1 - return m - - def fun2(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < n: - m += 1 - j += 1 - i += 1 - return m - - def fun3(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < i: - m += 1 - j += 1 - i += 1 - return m - - def fun4(self, n): - m = 0 - i = 1 - while i < n: - m += 1 - i = i * 2 - return m - - def fun5(self, n): - m = 0 - i = n - while i > 0: + j += 1 + i += 1 + return m + +def fun3(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < i: m += 1 - i = i / 2 - return m - - def fun6(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < n: - k = 0 - while k < n: - m += 1 - k += 1 - j += 1 - i += 1 - return m - - def fun7(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < n: - m += 1 - j += 1 - i += 1 - i = 0 - while i < n: + j += 1 + i += 1 + return m + +def fun4(n): + m = 0 + i = 1 + while i < n: + m += 1 + i = i * 2 + return m + +def fun5(n): + m = 0 + i = n + while i > 0: + m += 1 + i = i / 2 + return m + +def fun6(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < n: k = 0 while k < n: m += 1 k += 1 - i += 1 - return m - - def fun8(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < math.sqrt(n): - m += 1 - j += 1 - i += 1 - return m - - def fun9(self, n): - m = 0 - i = n - while i > 0: - j = 0 - while j < i: - m += 1 - j += 1 - i /= 2 - return m - - def fun10(self, n): - m = 0 - i = 0 - while i < n: - j = i - while j > 0: - m += 1 - j -= 1 - i += 1 - return m - - def fun11(self, n): - m = 0 - i = 0 - while i < n: - j = i - while j < n: - k = j + 1 - while k < n: - m += 1 - k += 1 - j += 1 - i += 1 - return m - - def fun12(self, n): - m = 0 - i = 0 - while i < n: - j = 0 - while j < n: - m += 1 - j += 1 - i += 1 - return m - - def fun13(self, n): - m = 0 - i = 1 - while i <= n: - j = 0 - while j <= i: + j += 1 + i += 1 + return m + +def fun7(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < n: + m += 1 + j += 1 + i += 1 + i = 0 + while i < n: + k = 0 + while k < n: + m += 1 + k += 1 + i += 1 + return m + +def fun8(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < math.sqrt(n): + m += 1 + j += 1 + i += 1 + return m + +def fun9(n): + m = 0 + i = n + while i > 0: + j = 0 + while j < i: + m += 1 + j += 1 + i /= 2 + return m + +def fun10(n): + m = 0 + i = 0 + while i < n: + j = i + while j > 0: + m += 1 + j -= 1 + i += 1 + return m + +def fun11(n): + m = 0 + i = 0 + while i < n: + j = i + while j < n: + k = j + 1 + while k < n: m += 1 - j += 1 - i *= 2 - return m - - @classmethod - def main(cls, args): - analysis = Analysis() - print "Value of M fun1():" , analysis.fun1(100) - print "Value of M fun2():" , analysis.fun2(100) - print "Value of M fun3():" , analysis.fun3(100) - print "Value of M fun4():" , analysis.fun4(100) - print "Value of M fun5():" , analysis.fun5(100) - print "Value of M fun6():" , analysis.fun6(100) - print "Value of M fun7():" , analysis.fun7(100) - print "Value of M fun8():" , analysis.fun8(100) - print "Value of M fun9():" , analysis.fun9(100) - print "Value of M fun10():" , analysis.fun10(100) - print "Value of M fun11():" , analysis.fun11(100) - print "Value of M fun12():" , analysis.fun12(100) - print "Value of M fun13():" , analysis.fun13(100) - - -if __name__ == '__main__': - import sys - Analysis.main(sys.argv) \ No newline at end of file + k += 1 + j += 1 + i += 1 + return m + +def fun12(n): + m = 0 + i = 0 + while i < n: + j = 0 + while j < n: + m += 1 + j += 1 + i += 1 + return m + +def fun13(n): + m = 0 + i = 1 + while i <= n: + j = 0 + while j <= i: + m += 1 + j += 1 + i *= 2 + return m + + +print "Value of M fun1():" , fun1(100) +print "Value of M fun2():" , fun2(100) +print "Value of M fun3():" , fun3(100) +print "Value of M fun4():" , fun4(100) +print "Value of M fun5():" , fun5(100) +print "Value of M fun6():" , fun6(100) +print "Value of M fun7():" , fun7(100) +print "Value of M fun8():" , fun8(100) +print "Value of M fun9():" , fun9(100) +print "Value of M fun10():" , fun10(100) +print "Value of M fun11():" , fun11(100) +print "Value of M fun12():" , fun12(100) +print "Value of M fun13():" , fun13(100) diff --git a/IntroductoryChapters/ArrayDemo.py b/IntroductoryChapters/ArrayDemo.py index 8a12bf2..76fb84e 100755 --- a/IntroductoryChapters/ArrayDemo.py +++ b/IntroductoryChapters/ArrayDemo.py @@ -1,39 +1,19 @@ #!/usr/bin/env python -""" generated source for module ArrayDemo """ class ArrayDemo(object): - """ generated source for class ArrayDemo """ def __init__(self): - """ generated source for method __init__ """ self.numbers = [0] * 100 def addValue(self, index, data): - """ generated source for method addValue """ self.numbers[index] = data def getValue(self, index): - """ generated source for method getValue """ return self.numbers[index] -""" generated source for module Main """ -class Main(object): - """ generated source for class Main """ - def __init__(self): - """ generated source for method __init__ """ - # TODO Auto-generated constructor stub - - @classmethod - def main(cls, args): - """ generated source for method main """ - # TODO Auto-generated method stub - d = ArrayDemo() - d.addValue(0, 1) - d.addValue(1, 2) - print d.getValue(0) - print d.getValue(1) - +d = ArrayDemo() +d.addValue(0, 1) +d.addValue(1, 2) +print d.getValue(0) +print d.getValue(1) -if __name__ == '__main__': - import sys - Main.main(sys.argv) diff --git a/IntroductoryChapters/Bulb.py b/IntroductoryChapters/Bulb.py index 3f947da..9b718f7 100755 --- a/IntroductoryChapters/Bulb.py +++ b/IntroductoryChapters/Bulb.py @@ -1,38 +1,24 @@ #!/usr/bin/env python class Bulb(object): - """ Source for class Bulb """ def __init__(self): # Constructor - """ Source for method __init__ """ self.isOn = False # Instance Variable def turnOn(self): # Instance Method - """ generated source for method turnOn """ self.isOn = True def turnOff(self): # Instance Method - """ generated source for method turnOff """ self.isOn = False def isOnFun(self): # Instance Method - """ generated source for method isOnFun """ return self.isOn -""" generated source for module BulbDemo """ -class BulbDemo(object): - """ generated source for class BulbDemo """ - @classmethod - def main(cls, args): - """ generated source for method main """ - b = Bulb() - print "bulb is on return : " , b.isOnFun() - b.turnOn() - print "bulb is on return : " , b.isOnFun() - - c = Bulb() - print "bulb c is on return : " , c.isOnFun() +b = Bulb() +print "bulb is on return : " , b.isOnFun() +b.turnOn() +print "bulb is on return : " , b.isOnFun() + +c = Bulb() +print "bulb c is on return : " , c.isOnFun() -if __name__ == '__main__': - import sys - BulbDemo.main(sys.argv) \ No newline at end of file diff --git a/IntroductoryChapters/Bulb2.py b/IntroductoryChapters/Bulb2.py index 3ed7087..f3f6cfe 100755 --- a/IntroductoryChapters/Bulb2.py +++ b/IntroductoryChapters/Bulb2.py @@ -1,50 +1,34 @@ #!/usr/bin/env python class Bulb(object): - """ Source for class Bulb """ # Class Variables TotalBulbCount = 0 # Constructor def __init__(self): - """ Source for method __init__ """ Bulb.TotalBulbCount += 1 self.isOn = False # Instance Variable # Class Method @classmethod def getBulbCount(cls): - """ Source for method getBulbCount """ return Bulb.TotalBulbCount # Instance Method def turnOn(self): - """ Source for method turnOn """ self.isOn = True # Instance Method def turnOff(self): - """ Source for method turnOff """ self.isOn = False # Instance Method def isOnFun(self): - """ Source for method isOnFun """ return self.isOn -""" Source for module BulbDemo """ -class BulbDemo(object): - """ Source for class BulbDemo """ - @classmethod - def main(cls, args): - """ Source for method main """ - b = Bulb() - print "bulb is on return : " , b.isOnFun() - b.turnOn() - print "bulb is on return : " , b.isOnFun() - print Bulb.getBulbCount() - -if __name__ == '__main__': - import sys - BulbDemo.main(sys.argv) \ No newline at end of file +b = Bulb() +print "bulb is on return : " , b.isOnFun() +b.turnOn() +print "bulb is on return : " , b.isOnFun() +print Bulb.getBulbCount() diff --git a/IntroductoryChapters/Bulb3.py b/IntroductoryChapters/Bulb3.py index 334e55d..d2cc2c9 100755 --- a/IntroductoryChapters/Bulb3.py +++ b/IntroductoryChapters/Bulb3.py @@ -1,59 +1,39 @@ #!/usr/bin/env python -""" Documentation of module Bulb """ class Bulb(object): - """ Documentation of class Bulb """ TotalBulbCount = 0 # Class Variables def __init__(self): # Constructor - """ Documentation of method __init__ """ Bulb.TotalBulbCount += 1 self.isOn = False # Instance Variables @classmethod def getBulbCount(cls): - """ Documentation of method getBulbCount """ return cls.TotalBulbCount def turnOn(self): # Instance Method - """ Documentation of method turnOn """ self.isOn = True def turnOff(self): # Instance Method - """ Documentation of method turnOff """ self.isOn = False def isOnFun(self): # Instance Method - """ Documentation of method isOnFun """ return self.isOn class AdvanceBulb(Bulb): - """ Documentation of class AdvanceBulb """ def __init__(self): # Constructor - """ Documentation of method __init__ """ self.intensity = 0 # Instance Variables Bulb.__init__(self) def setIntersity(self, i): # Instance Method - """ Documentation of method setIntersity """ self.intensity = i def getIntersity(self, i): # Instance Method - """ Documentation of method setIntersity """ return self.intensity -""" Documentation of module BulbDemo """ -class BulbDemo(object): - """ Documentation of class BulbDemo """ - @classmethod - def main(cls, args): - """ Documentation of method main """ - # b = Bulb() - c = AdvanceBulb() - print Bulb.getBulbCount() - print c.isOnFun() -if __name__ == '__main__': - import sys - BulbDemo.main(sys.argv) \ No newline at end of file +# b = Bulb() +c = AdvanceBulb() +print Bulb.getBulbCount() +print c.isOnFun() diff --git a/IntroductoryChapters/BulbEnum.py b/IntroductoryChapters/BulbEnum.py index a7ed451..8bf3a77 100755 --- a/IntroductoryChapters/BulbEnum.py +++ b/IntroductoryChapters/BulbEnum.py @@ -1,32 +1,26 @@ #!/usr/bin/env python class Bulb(object): - """ Source for class Bulb """ class BulbSize: - """ Source for enum BulbSize """ SMALL = u'SMALL' MEDIUM = u'MEDIUM' LARGE = u'LARGE' # Constructor def __init__(self): - """ Source for method __init__ """ self.isOn = False # Instance Variables self.size = Bulb.BulbSize.MEDIUM # Instance Method def turnOn(self): - """ Source for method turnOn """ self.isOn = True # Instance Method def turnOff(self): - """ Source for method turnOff """ self.isOn = False # Instance Method def isOnFun(self): - """ Source for method isOnFun """ return self.isOn def getBulbSize(self): @@ -35,14 +29,6 @@ def getBulbSize(self): def setBulbSize(self, value): self.size = value -class BulbDemo(object): - """ Source for class BulbDemo """ - @classmethod - def main(cls, args): - """ Source for method main """ - b = Bulb() - print "Bulb Size : " + b.getBulbSize() - -if __name__ == '__main__': - import sys - BulbDemo.main(sys.argv) \ No newline at end of file + +b = Bulb() +print "Bulb Size : " + b.getBulbSize() diff --git a/IntroductoryChapters/BulbInterface.py b/IntroductoryChapters/BulbInterface.py index cc584eb..83f9f62 100755 --- a/IntroductoryChapters/BulbInterface.py +++ b/IntroductoryChapters/BulbInterface.py @@ -2,31 +2,24 @@ from abc import ABCMeta from abc import abstractmethod -""" Source for module BulbInterface """ class BulbInterface(object): - """ Source for interface BulbInterface """ __metaclass__ = ABCMeta @abstractmethod def turnOn(self): - """ Source for method turnOn """ pass @abstractmethod def turnOff(self): - """ Source for method turnOff """ pass @abstractmethod def isOnFun(self): - """ Source for method isOnFun """ pass # implements BulbInterface class Bulb(BulbInterface): - """ Source for class Bulb """ class BulbSize: - """ Source for enum BulbSize """ SMALL = u'SMALL' MEDIUM = u'MEDIUM' LARGE = u'LARGE' @@ -36,7 +29,6 @@ class BulbSize: # Constructor def __init__(self): - """ Source for method __init__ """ Bulb.TotalBulbCount += 1 self.isOn = False # Instance Variables self.size = Bulb.BulbSize.MEDIUM @@ -44,59 +36,41 @@ def __init__(self): # Class Method @classmethod def getBulbCount(cls): - """ Source for method getBulbCount """ return cls.TotalBulbCount # Instance Method def turnOn(self): - """ Source for method turnOn """ self.isOn = True # Instance Method def turnOff(self): - """ Source for method turnOff """ self.isOn = False # Instance Method def isOnFun(self): - """ Source for method isOnFun """ return self.isOn def getBulbSize(self): return self.size class AdvanceBulb(Bulb): - """ Source for class AdvanceBulb """ # Constructor def __init__(self): - """ Source for method __init__ """ self.intensity = 0 # Instance Variables Bulb.__init__(self) # Instance Method def setIntersity(self, i): - """ Source for method setIntersity """ self.intensity = i # Instance Method def getIntersity(self, i): - """ Source for method setIntersity """ return self.intensity -""" Source for module BulbDemo """ -class BulbDemo(object): - """ Source for class BulbDemo """ - @classmethod - def main(cls, args): - """ Source for method main """ - b = Bulb() - print "Bulb Size : " + b.getBulbSize() - print "bulb is on return : " , b.isOnFun() - b.turnOn() - print "bulb is on return : " , b.isOnFun() - -if __name__ == '__main__': - import sys - BulbDemo.main(sys.argv) +b = Bulb() +print "Bulb Size : " + b.getBulbSize() +print "bulb is on return : " , b.isOnFun() +b.turnOn() +print "bulb is on return : " , b.isOnFun() diff --git a/IntroductoryChapters/Calculator.py b/IntroductoryChapters/Calculator.py index 41936f9..47e255e 100755 --- a/IntroductoryChapters/Calculator.py +++ b/IntroductoryChapters/Calculator.py @@ -1,31 +1,22 @@ #!/usr/bin/env python -""" generated source for module Calculator """ class Calculator(object): - """ generated source for class Calculator """ def __init__(self, value=0): - """ generated source for method __init__ """ self.value = value def reset(self): - """ generated source for method reset """ self.value = 0 def getValue(self): - """ generated source for method getValue """ return self.value def add(self, data): - """ generated source for method add """ self.value = self.value + data def increment(self): - """ generated source for method increment """ self.value += 1 def subtract(self, data): - """ generated source for method subtract """ self.value = self.value - data def decrement(self): - """ generated source for method decrement """ - self.value -= 1 \ No newline at end of file + self.value -= 1 diff --git a/IntroductoryChapters/Circle.py b/IntroductoryChapters/Circle.py index 2a11bb3..2278d34 100755 --- a/IntroductoryChapters/Circle.py +++ b/IntroductoryChapters/Circle.py @@ -1,7 +1,6 @@ #!/usr/bin/env python from Shape import Shape import math -""" Source for module Circle """ class Circle(Shape): def __init__(self, r=1): self.radius = r @@ -13,4 +12,4 @@ def area(self): return math.pi * math.pow(self.radius, 2) def perimeter(self): - return 2 * math.pi * self.radius \ No newline at end of file + return 2 * math.pi * self.radius diff --git a/IntroductoryChapters/Circle.pyc b/IntroductoryChapters/Circle.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec7e478e8fd4d3b0c4c3b19116dc8098fb406a68 GIT binary patch literal 1574 zcmd5*O>fjN5FKx}g_af})DyoTm%xn!LI~K3kISlZ#DOSMlxE$=RX$es1hlBP_P~GR z=kNnyo|6TsH%@GJJsCUp%)Ix;(a+<<@9%zO6-`eh@7FT?b1^IVD{6>ZqKrskKBGoa zrf3zBA-WJ}PPariM4z)6KBw`X9JRmXiIsSaX)Jm2}vr1*^ULm9gDeEbWKzQAZaLOIhKSvT)DD?k8z0S zIANL#Ml2VLpDGEN6m7-|nnlv)ixCa`$G(Kq1 w^;g8;{pVY&w_WR@z`i<)4&)aHVPt`HPzRfKtM0)1%aP|-=s1s-e58)lZz>~&#sB~S literal 0 HcmV?d00001 diff --git a/IntroductoryChapters/ForDemo.py b/IntroductoryChapters/ForDemo.py index 3619c1c..0486310 100755 --- a/IntroductoryChapters/ForDemo.py +++ b/IntroductoryChapters/ForDemo.py @@ -1,44 +1,35 @@ #!/usr/bin/env python -""" generated source for module ForDemo """ -class ForDemo(object): - """ generated source for class ForDemo """ - text = "Hello, World!" - PI = 3.141592653589793 +text = "Hello, World!" +PI = 3.141592653589793 - @classmethod - def main1(cls): - """ generated source for method main1 """ - numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - totalsum = 0 - for n in numbers: - totalsum += n - print "Sum is :: " , totalsum +def main1(): + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + totalsum = 0 + for n in numbers: + totalsum += n + print "Sum is :: " , totalsum - @classmethod - def main2(cls): - """ generated source for method main2 """ - numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - totalsum = 0 - i = 0 - while i < len(numbers): - totalsum += numbers[i] - i += 1 - print "Sum is :: " , totalsum +def main2(): + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + totalsum = 0 + i = 0 + while i < len(numbers): + totalsum += numbers[i] + i += 1 + print "Sum is :: " , totalsum - @classmethod - def main(cls, args): - """ generated source for method main """ - numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - totalsum = 0 - i = 0 - while True: - totalsum += numbers[i] - i += 1 - if i >= len(numbers): - break - print "Sum is :: " , totalsum +def main3(): + numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + totalsum = 0 + i = 0 + while True: + totalsum += numbers[i] + i += 1 + if i >= len(numbers): + break + print "Sum is :: " , totalsum -if __name__ == '__main__': - import sys - ForDemo.main(sys.argv) +main1() +main2() +main3() diff --git a/IntroductoryChapters/HelloWorld.py b/IntroductoryChapters/HelloWorld.py index 84c8990..43f01cb 100755 --- a/IntroductoryChapters/HelloWorld.py +++ b/IntroductoryChapters/HelloWorld.py @@ -1,13 +1,4 @@ #!/usr/bin/env python -""" source for module HelloWorld """ -class HelloWorld(object): - """ source for class HelloWorld """ - @classmethod - def main(cls, args): - """ source for method main """ - print "Hello, World!" +print "Hello, World!" -if __name__ == '__main__': - import sys - HelloWorld.main(sys.argv) \ No newline at end of file diff --git a/IntroductoryChapters/Incriment.py b/IntroductoryChapters/Incriment.py index 7cd5c24..f91f185 100755 --- a/IntroductoryChapters/Incriment.py +++ b/IntroductoryChapters/Incriment.py @@ -1,38 +1,31 @@ #!/usr/bin/env python -""" Source for module Introduction """ -class IncrementDemo(object): - """ Source for class Introduction """ - @classmethod - def increment2(cls, var): - """ Source for method increment """ - var += 1 - @classmethod - def main2(cls, args): - """ Source for method main """ - var = 1 - print "Value before increment :" , var - cls.increment(var) - print "Value after increment :" , var - - class MyInt(object): - """ Source for class MyInt """ - value = 0 +def increment1(var): + """ Source for method increment """ + var += 1 - @classmethod - def increment(cls, value): - """ Source for method increment """ - value.value += 1 - - @classmethod - def main(cls, args): - """ Source for method main """ - var = cls.MyInt() - print "Value before increment :" , var.value - cls.increment(var) - print "Value after increment :" , var.value +def main1(): + """ Source for method main """ + var = 1 + print "Value before increment :" , var + increment1(var) + print "Value after increment :" , var + +class MyInt(object): + def __init__(self): + self.value = 1 + +def increment2(value): + """ Source for method increment """ + value.value += 1 + +def main2(): + """ Source for method main """ + var = MyInt() + print "Value before increment :" , var.value + increment2(var) + print "Value after increment :" , var.value -if __name__ == '__main__': - import sys - IncrementDemo.main(sys.argv) \ No newline at end of file +main1() +main2() diff --git a/IntroductoryChapters/Introduction.py b/IntroductoryChapters/Introduction.py index 803790c..8dae6fb 100755 --- a/IntroductoryChapters/Introduction.py +++ b/IntroductoryChapters/Introduction.py @@ -1,374 +1,388 @@ #!/usr/bin/env python -""" Source for module Introduction """ -from ctypes.test.test_simplesubclasses import MyInt -class Introduction(object): - """ Source for class Introduction """ + +def increment1(var): + """ Source for method increment """ + var += 1 + +def main1(): + """ Source for method main """ + var = 1 + print "Value before increment :" , var + increment1(var) + print "Value after increment :" , var - @classmethod - def main(cls, args): - i = 1 - cls.increment(i) - print i - var = MyInt() - var.value = 1 - cls.increment2(var) - print var.value +class MyInt(object): + def __init__(self): + self.value = 1 + +def increment2(value): + """ Source for method increment """ + value.value += 1 - @classmethod - def increment(cls, var): - var += 1 - - class MyInt(object): - value = 0 - - @classmethod - def increment2(cls, value): - value.value += 1 - - @classmethod - def swap(cls, arr, x, y): - temp = arr[x] - arr[x] = arr[y] - arr[y] = temp - - - @classmethod - def permutation(cls, arr, i, length): - if length == i: - print arr - return - j = i - while j < length: - cls.swap(arr, i, j) - cls.permutation(arr, i + 1, length) - cls.swap(arr, i, j) +def main2(): + """ Source for method main """ + var = MyInt() + print "Value before increment :" , var.value + increment2(var) + print "Value after increment :" , var.value + + +def swap(arr, x, y): + temp = arr[x] + arr[x] = arr[y] + arr[y] = temp + + +def permutation(arr, i, length): + if length == i: + print arr + return + j = i + while j < length: + swap(arr, i, j) + permutation(arr, i + 1, length) + swap(arr, i, j) + j += 1 + + + + +def main3(): + arr = [None] * 5 + i = 0 + while i < 5: + arr[i] = i + i += 1 + permutation(arr, 0, 5) + + +def GCD(m, n): + if m < n: + return (GCD(n, m)) + if m % n == 0: + return (n) + return (GCD(n, m % n)) + + +def main4(): + print GCD(5, 2) + + +def towerOfHanoi(num, src, dst, temp): + """ Source for method towerOfHanoi """ + if num < 1: + return + towerOfHanoi(num - 1, src, temp, dst) + print "Move " , num , " disk from peg " , src , " to peg " , dst + towerOfHanoi(num - 1, temp, dst, src) + + +def main5(): + num = 4 + print "The sequence of moves involved in the Tower of Hanoi are :" + towerOfHanoi(num, 'A', 'C', 'B') + + +def function2(): + print "fun2 line 1" + + +def function1(): + print "fun1 line 1" + function2() + print "fun1 line 2" + + +def main6(): + print "main line 1" + function1() + print "main line 2" + + +def maxSubArraySum(arr): + size = len(arr) + maxSoFar = 0 + maxEndingHere = 0 + i = 0 + while i < size: + maxEndingHere = maxEndingHere + arr[i] + if maxEndingHere < 0: + maxEndingHere = 0 + if maxSoFar < maxEndingHere: + maxSoFar = maxEndingHere + i += 1 + return maxSoFar + + + +def main7(): + arr = [1, -2, 3, 4, -4, 6, -4, 8, 2] + print maxSubArraySum(arr) + + + + +def variableExample(): + var1 = 100 + var2 = 200 + var3 = var1 + var2 + print "Adding" , var1 , "and" , var2 , "will give" , var3 + + +def arrayExample(): + arr = [0] * 10 + i = 0 + while i < 10: + arr[i] = i + i += 1 + return arr + printArray1(arr, 10) + + +def printArray1(arr): + count = len(arr) + i = 0 + while i < count: + print arr[i], + i += 1 + + +def main8(): + twoDArrayExample() + + + +def twoDArrayExample(): + first = 4 + second = 4 + arr = [[0 for x in range(first)] for y in range(second) ] + count = 0 + i = 0 + while i < first: + j = 0 + while j < second: + arr[i][j] = count + count += 1 j += 1 + i += 1 + print2DArray(arr, first, second) +def print2DArray(arr, row, col): + i = 0 + while i < row: + j = 0 + while j < col: + print arr[i][j], + j += 1 + i += 1 - @classmethod - def main4444(cls, args): - arr = [None] * 5 - i = 0 - while i < 5: - arr[i] = i - i += 1 - cls.permutation(arr, 0, 5) - - @classmethod - def GCD(cls, m, n): - if m < n: - return (cls.GCD(n, m)) - if m % n == 0: - return (n) - return (cls.GCD(n, m % n)) - - @classmethod - def main555(cls, args): - print cls.GCD(5, 2) - - @classmethod - def towerOfHanoi(cls, num, src, dst, temp): - """ Source for method towerOfHanoi """ - if num < 1: - return - cls.towerOfHanoi(num - 1, src, temp, dst) - print "Move " , num , " disk from peg " , src , " to peg " , dst - cls.towerOfHanoi(num - 1, temp, dst, src) - - @classmethod - def main1111(cls, args): - num = 4 - print "The sequence of moves involved in the Tower of Hanoi are :" - cls.towerOfHanoi(num, 'A', 'C', 'B') - - @classmethod - def function2(cls): - print "fun2 line 1" - - @classmethod - def function1(cls): - print "fun1 line 1" - cls.function2() - print "fun1 line 2" - - @classmethod - def main96(cls, args): - print "main line 1" - cls.function1() - print "main line 2" - - @classmethod - def maxSubArraySum(cls, arr): - size = len(arr) - maxSoFar = 0 - maxEndingHere = 0 - i = 0 - while i < size: - maxEndingHere = maxEndingHere + arr[i] - if maxEndingHere < 0: - maxEndingHere = 0 - if maxSoFar < maxEndingHere: - maxSoFar = maxEndingHere - i += 1 - return maxSoFar - - - @classmethod - def main975(cls, args): - arr = [1, -2, 3, 4, -4, 6, -4, 8, 2] - print cls.maxSubArraySum(arr) - +def main9(): + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + print SumArray(arr) - @classmethod - def variableExample(cls): - var1 = 100 - var2 = 200 - var3 = var1 + var2 - print "Adding" , var1 , "and" , var2 , "will give" , var3 - - @classmethod - def arrayExample(cls): - arr = [0] * 10 - i = 0 - while i < 10: - arr[i] = i - i += 1 - return arr - cls.printArray1(arr, 10) - - @classmethod - def printArray1(cls, arr): - count = len(arr) - i = 0 - while i < count: - print arr[i], - i += 1 - - @classmethod - def main100(cls, args): - cls.twoDArrayExample() - - - @classmethod - def twoDArrayExample(cls): - first = 4 - second = 4 - arr = [[0 for x in range(first)] for y in range(second) ] - count = 0 - i = 0 - while i < first: - j = 0 - while j < second: - arr[i][j] = count - count += 1 - j += 1 - i += 1 - cls.print2DArray(arr, first, second) - - @classmethod - def print2DArray(cls, arr, row, col): - i = 0 - while i < row: - j = 0 - while j < col: - print arr[i][j], - j += 1 - i += 1 - - @classmethod - def main99(cls, args): - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] - print cls.SumArray(arr) - - - @classmethod - def SumArray(cls, arr): - size = len(arr) - total = 0 - index = 0 - while index < size: - total = total + arr[index] - index += 1 - return total - - @classmethod - def SequentialSearch(cls, arr, value): - size = len(arr) - i = 0 - while i < size: - if value == arr[i]: - return True - i += 1 - return False - - @classmethod - def BinarySearch(cls, arr, value): - size = len(arr) - low = 0 - high = size - 1 - while low <= high: - mid = low + (high - low) / 2 - if arr[mid] == value: - return True - else: - if arr[mid] < value: - low = mid + 1 - else: - high = mid - 1 - return False - - @classmethod - def main98(cls, args): - - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] - print cls.BinarySearch(arr, 6) - - - @classmethod - def rotateArray(cls, arr, k): - - n = len(arr) - cls.reverseArray(arr, 0, k - 1) - cls.reverseArray(arr, k, n - 1) - cls.reverseArray(arr, 0, n - 1) - - @classmethod - def reverseArray(cls, arr, start, end): - i = start - j = end - while i < j: - temp = arr[i] - arr[i] = arr[j] - arr[j] = temp - i += 1 - j -= 1 - - @classmethod - def reverseArray_0(cls, a): - start = 0 - end = len(a) - i = start - j = end - while i < j: - temp = a[i] - a[i] = a[j] - a[j] = temp - i += 1 - j -= 1 - - @classmethod - def main97(cls, args): - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] - cls.rotateArray(arr, 3) - print arr - - - class coord(object): - x = int() - y = int() - - def main2(self): - point = self.coord() - point.x = 10 - point.y = 10 - print "X axis coord value is " + point.x - print "Y axis coord value is " + point.y - - - class student(object): - rollNo = int() - firstName = str() - lastName = str() - - def main3(self): - stud = self.student() - refStud = stud - refStud.rollNo = 1 - refStud.firstName = "john" - refStud.lastName = "smith" - print "Roll No: Student Name: " + refStud.rollNo + refStud.firstName + refStud.lastName - - - def main4(self): - x = 10 - y = 20 - result = sum(x, y) - print "Sum is : " + result - - - def sum(self, num1, num2): - result = num1 + num2 - return result - - @classmethod - def factorial(cls, i): - if i <= 1: - return 1 - return i * cls.factorial(i - 1) - - @classmethod - def main95(cls, args): - print cls.factorial(5) - - - @classmethod - def printInt(cls, number): - conversion = "0123456789" - digit = number % 10 - number = number / 10 - temp = "" - if number != 0: - temp += cls.printInt(number) - temp += conversion[digit] - return temp - - @classmethod - def main3232(cls, args): - print cls.printInt2(50, 2) - - @classmethod - def printInt2(cls, number, base): - conversion = "0123456789ABCDEF" - digit = number % base - number = number / base - temp = "" - if number != 0: - temp += cls.printInt2(number, base) - temp += conversion[digit] - return temp - - @classmethod - def fibonacci(cls, n): - if n <= 1: - return n - return cls.fibonacci(n - 1) + cls.fibonacci(n - 2) - - @classmethod - def main7777(cls, args): - print cls.fibonacci(6) - - @classmethod - def BinarySearchRecursive(cls, arr, low, high, value): + +def SumArray(arr): + size = len(arr) + total = 0 + index = 0 + while index < size: + total = total + arr[index] + index += 1 + return total + + +def SequentialSearch(arr, value): + size = len(arr) + i = 0 + while i < size: + if value == arr[i]: + return True + i += 1 + return False + + +def BinarySearch(arr, value): + size = len(arr) + low = 0 + high = size - 1 + while low <= high: mid = low + (high - low) / 2 if arr[mid] == value: - return mid - elif arr[mid] < value: - return cls.BinarySearchRecursive(arr, mid + 1, high, value) + return True else: - return cls.BinarySearchRecursive(arr, low, mid - 1, value) + if arr[mid] < value: + low = mid + 1 + else: + high = mid - 1 + return False - @classmethod - def main3213(cls, args): - arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] - print cls.BinarySearch(arr, 6) - print cls.BinarySearch(arr, 16) +def main10(): - -if __name__ == '__main__': - import sys - Introduction.main(sys.argv) + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + print BinarySearch(arr, 6) + + + +def rotateArray(arr, k): + + n = len(arr) + reverseArray(arr, 0, k - 1) + reverseArray(arr, k, n - 1) + reverseArray(arr, 0, n - 1) + + +def reverseArray(arr, start, end): + i = start + j = end + while i < j: + temp = arr[i] + arr[i] = arr[j] + arr[j] = temp + i += 1 + j -= 1 + + +def reverseArray_0(a): + start = 0 + end = len(a) + i = start + j = end + while i < j: + temp = a[i] + a[i] = a[j] + a[j] = temp + i += 1 + j -= 1 + + +def main11(): + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + rotateArray(arr, 3) + print arr + + + +class coord(object): + x = int() + y = int() + +def main12(): + point = coord() + point.x = 10 + point.y = 10 + print "X axis coord value is " , point.x + print "Y axis coord value is " , point.y + + +class student(object): + rollNo = int() + firstName = str() + lastName = str() + +def main13(): + stud = student() + refStud = stud + refStud.rollNo = 1 + refStud.firstName = "john" + refStud.lastName = "smith" + print "Roll No: Student Name: " , refStud.rollNo , refStud.firstName , refStud.lastName + +def main14(): + x = 10 + y = 20 + result = sum(x, y) + print "Sum is : " , result + + +def sum(num1, num2): + result = num1 + num2 + return result + + +def factorial(i): + if i <= 1: + return 1 + return i * factorial(i - 1) + + +def main15(): + print factorial(5) + + + +def printInt(number): + conversion = "0123456789" + digit = number % 10 + number = number / 10 + temp = "" + if number != 0: + temp += printInt(number) + temp += conversion[digit] + return temp + + +def main16(): + print printInt2(50, 2) + + +def printInt2(number, base): + conversion = "0123456789ABCDEF" + digit = number % base + number = number / base + temp = "" + if number != 0: + temp += printInt2(number, base) + temp += conversion[digit] + return temp + + +def fibonacci(n): + if n <= 1: + return n + return fibonacci(n - 1) + fibonacci(n - 2) + + +def main17(): + print fibonacci(6) + + +def BinarySearchRecursive(arr, low, high, value): + mid = low + (high - low) / 2 + if arr[mid] == value: + return mid + elif arr[mid] < value: + return BinarySearchRecursive(arr, mid + 1, high, value) + else: + return BinarySearchRecursive(arr, low, mid - 1, value) + + + +def main18(): + arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] + print BinarySearch(arr, 6) + print BinarySearch(arr, 16) + + +main1() +main2() +main3() +main4() +main5() +main6() +main7() +main8() +main9() +main10() +main11() +main12() +main13() +main14() +main15() +main16() +main17() +main18() diff --git a/IntroductoryChapters/LinkedList.py b/IntroductoryChapters/LinkedList.py index b3829eb..ca6f47f 100755 --- a/IntroductoryChapters/LinkedList.py +++ b/IntroductoryChapters/LinkedList.py @@ -1,15 +1,10 @@ #!/usr/bin/env python -""" Documentation of module LinkedList """ class LinkedList(object): - """ Documentation of class LinkedList """ class Node(object): - """ Documentation of class Node """ def __init__(self, v, n=None): - """ Documentation of for method __init__ """ self.value = v self.next = n def __init__(self): - """ Documentation of method __init__ """ - self.head = None \ No newline at end of file + self.head = None diff --git a/IntroductoryChapters/Rectangle.py b/IntroductoryChapters/Rectangle.py index bd2446f..aee6a87 100755 --- a/IntroductoryChapters/Rectangle.py +++ b/IntroductoryChapters/Rectangle.py @@ -1,26 +1,19 @@ #!/usr/bin/env python from Shape import Shape -""" generated source for module Rectangle """ class Rectangle(Shape): - """ generated source for class Rectangle """ def __init__(self, w=1, l=1): - """ generated source for method __init__ """ self.width = w self.length = l def setWidth(self, w): - """ generated source for method setWidth """ self.width = w def setLength(self, l): - """ generated source for method setLength """ self.length = l def area(self): - """ generated source for method area """ return self.width * self.length # Area = width * length def perimeter(self): - """ generated source for method perimeter """ return 2 * (self.width + self.length) # Perimeter = 2(width + length) diff --git a/IntroductoryChapters/Rectangle.pyc b/IntroductoryChapters/Rectangle.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7672851809c955010211afd3092e3d1dacddde0b GIT binary patch literal 1811 zcmd5++iuf95FO`INKv^7!7o@y<^upBAeEpJs;adR!m?z!_BLMROXQtUMJiA9@AwOT zfe(N=6Q>m3cp^?_GP9oS%$YO0;~xk6-;cf}1r5(weqW0C$D&I422>L@Lr<7 z1yqjdlISbZ$3&b7#o<)K-A{SKKrDtESNYQNOe|vy&f7(8|48#%-uP#tWKV3f&38GX zWJHonQY7OcS295!tW2q#sT=A1_{_p5?ez4g(ndeQZctHwtwkC>A+S6!PPwcK~5 zM0NdoF0Ewbx$5MT<(h9w1zF}=$62PuLQyaa3Lx8x_ToSmu6j`lH$w{m%^*^nVX%P# zcRPpETmAr+fZ3y9`d5_T^cqUAy;CT0Pz2>Woxodg2AJRo0$0hrErv|>r;QHi!In)# zD4RyXD!HI^r*NX6ytg?}{0$LhE5!R^$klTlRMgcwbhstdSF6i)#>IFziMzP`ou5ir-YK_5W`ngDC?A9yRU-cP6tj bKAY>+$Qo(L&K0ihf4*t>3k;HSb2s<}OsmKJ literal 0 HcmV?d00001 diff --git a/IntroductoryChapters/Shape.py b/IntroductoryChapters/Shape.py index a399800..613bf0d 100755 --- a/IntroductoryChapters/Shape.py +++ b/IntroductoryChapters/Shape.py @@ -2,18 +2,14 @@ from abc import ABCMeta from abc import abstractmethod -""" generated source for module Shape """ # Abstract Class class Shape(object): - """ generated source for class Shape """ __metaclass__ = ABCMeta @abstractmethod def area(self): - """ generated source for method area """ pass @abstractmethod def perimeter(self): - """ generated source for method perimeter """ - pass \ No newline at end of file + pass diff --git a/IntroductoryChapters/Shape.pyc b/IntroductoryChapters/Shape.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2aa6804fc61a0844128d33e1f59aad2839770fe5 GIT binary patch literal 1074 zcmd5*%TC-t5bUvc7lK6KGkl2o02D=mMG72(kSz|ZELmf_VIBFgnrTPcbMklj96lha zo`rDb29~Ei)t+`&O^xHn!-L1GKdYLat{Bg+82%KY!ELA`>J6<78O2e+5v?NNm^h|; zL(PnS6a6B(Tg|AMQ=TkP-u}gv7|di3;p}|*oyG1FACa(?7iVkfS=M7CbENXM-SB@h z5i;i({u2U|a$s~uS9GD!62#^KnrFD6EKjtu*3Qpksh^o4pe_#-t`i{IvC$WvyZc>A z^L~r4JS}cLJ7281w}TWHV?Fgeh%dgiayeDSjT@_u`!pZBpY8CFwnKVh#iqHqsg}vH zPtUrC(Y3PfeL8tvbF+oop|~2vjSW_fZo7nP(LO=`$!04`$U3$kl!}U>==E|kHSyg@ zQ3)G%EnH@I2=JsQ(K8|Y2xU3gp371W0_d?V9bg7Tq7`L{Vq16Cd!*IUOgAXg6Z4`o z%-+_wOs&$R?=>vUB08E~CrVS)6I<0mRFELLWUPL0EurjP2?@S@-Z}9_MTLLo*c`|I E03c)#n*aa+ literal 0 HcmV?d00001 diff --git a/IntroductoryChapters/ShapeDemo.py b/IntroductoryChapters/ShapeDemo.py index 10838c5..dcdef3b 100755 --- a/IntroductoryChapters/ShapeDemo.py +++ b/IntroductoryChapters/ShapeDemo.py @@ -2,18 +2,12 @@ from Circle import Circle from Rectangle import Rectangle -class ShapeDemo(object): - @classmethod - def main(cls, args): - width = 2 - length = 3 - rectangle = Rectangle(width, length) - print "Rectangle width:" , width , "and length:" , length , "Area:" , rectangle.area() , "Perimeter:" , rectangle.perimeter() - radius = 10 - circle = Circle(radius) - print "Circle radius:" , radius, "Area:" , circle.area(), "Perimeter:" , circle.perimeter() +width = 2 +length = 3 +rectangle = Rectangle(width, length) +print "Rectangle width:" , width , "and length:" , length , "Area:" , rectangle.area() , "Perimeter:" , rectangle.perimeter() +radius = 10 +circle = Circle(radius) +print "Circle radius:" , radius, "Area:" , circle.area(), "Perimeter:" , circle.perimeter() -if __name__ == '__main__': - import sys - ShapeDemo.main(sys.argv) diff --git a/IntroductoryChapters/Tree.py b/IntroductoryChapters/Tree.py index 1468724..58edb1a 100755 --- a/IntroductoryChapters/Tree.py +++ b/IntroductoryChapters/Tree.py @@ -1,17 +1,12 @@ #!/usr/bin/env python -""" Documentation of module Tree """ class Tree(object): - """ Documentation of class Tree """ class Node(object): - """ Documentation of class Node """ def __init__(self, v, l=None, r=None): - """ Documentation of method __init__ """ self.value = v self.lChild = l self.rChild = r # Nested Class Node other fields and methods. def __init__(self): - """ Documentation of method __init__ """ self.root = None - # Outer Class Tree other fields and methods. \ No newline at end of file + # Outer Class Tree other fields and methods. diff --git a/IntroductoryChapters/minmaxliit.py b/IntroductoryChapters/minmaxliit.py index daf9ca6..87a4cf1 100755 --- a/IntroductoryChapters/minmaxliit.py +++ b/IntroductoryChapters/minmaxliit.py @@ -1,19 +1,13 @@ #!/usr/bin/env python -class VariableType(object): - @classmethod - def main(cls, args): - maxInt = sys.maxint - longstart = maxInt + 1 - minInt = -1 * (maxInt+1) - floatvalue = 0.1 - str = "hello, world!" - print "type of maxint" , type(maxInt) , "value : " , maxInt - print "type of minInt" , type(minInt) , "value : " , minInt - print "type of longstart" , type(longstart) , "value : " , longstart - print "type of floatvalue" , type(floatvalue) , "value : " , floatvalue - print "type of str" , type(str) , "value : " , str +import sys - -if __name__ == '__main__': - import sys - VariableType.main(sys.argv) \ No newline at end of file +maxInt = sys.maxint +longstart = maxInt + 1 +minInt = -1 * (maxInt+1) +floatvalue = 0.1 +str = "hello, world!" +print "type of maxint" , type(maxInt) , "value : " , maxInt +print "type of minInt" , type(minInt) , "value : " , minInt +print "type of longstart" , type(longstart) , "value : " , longstart +print "type of floatvalue" , type(floatvalue) , "value : " , floatvalue +print "type of str" , type(str) , "value : " , str diff --git a/IntroductoryChapters/type.py b/IntroductoryChapters/type.py index e39a8b5..08d6af3 100755 --- a/IntroductoryChapters/type.py +++ b/IntroductoryChapters/type.py @@ -1,35 +1,30 @@ #!/usr/bin/env python -class TypeDemo(object): +import sys - @classmethod - def main(cls, args): - value1 = sys.maxint - value2 = value1 + 1 - value3 = 13.05 - value4 = 3.14j - value5 = "hello, world!" - print type(value1),value2, type(value2), type(value3), type(value4),type(value5), value5 +value1 = sys.maxint +value2 = value1 + 1 +value3 = 13.05 +value4 = 3.14j +value5 = "hello, world!" +print type(value1),value2, type(value2), type(value3), type(value4),type(value5), value5 -if __name__ == '__main__': - import sys - TypeDemo.main(sys.argv) +# Parameter Passing +def Change1(B): + B = 2 + +A = 1 +Change1(A) +print A + -class ParameterPass: - def __init__(self): - A = 1 - self.Change(A) - print A +# Parameter Passing 2 +def Change2(B): + B.append(2) - def Change(self, B): - B = 2 +A = [1] +Change2(A) +print A -class ParameterPass2: - def __init__(self): - A = [1] - self.Change(A) - print A - def Change(self, B): - B.append(2) diff --git a/LinkedList/CircularLinkedList.py b/LinkedList/CircularLinkedList.py index b8984ab..22f6c76 100755 --- a/LinkedList/CircularLinkedList.py +++ b/LinkedList/CircularLinkedList.py @@ -125,25 +125,20 @@ def printList(self): temp = temp.next print temp.value, -class CircularLinkedListDemo(object): - @classmethod - def main(cls, args): - ll = CircularLinkedList() - ll.addHead(1) - ll.addHead(2) - ll.addHead(3) - ll.addHead(1) - ll.addHead(2) - ll.addHead(3) - print ll.size() - ll.printList() - print() - ll2 = ll.copyList() - ll2.printList() - print() - ll3 = ll.copyListReversed() - ll3.printList() -if __name__ == '__main__': - import sys - CircularLinkedListDemo.main(sys.argv) \ No newline at end of file +ll = CircularLinkedList() +ll.addHead(1) +ll.addHead(2) +ll.addHead(3) +ll.addHead(1) +ll.addHead(2) +ll.addHead(3) +print ll.size() +ll.printList() +print() +ll2 = ll.copyList() +ll2.printList() +print() +ll3 = ll.copyListReversed() +ll3.printList() + diff --git a/LinkedList/DoublyCircularLinkedList.py b/LinkedList/DoublyCircularLinkedList.py index 8f60fd1..4807ebf 100755 --- a/LinkedList/DoublyCircularLinkedList.py +++ b/LinkedList/DoublyCircularLinkedList.py @@ -112,20 +112,13 @@ def printList(self): print temp.value, - @classmethod - def main(cls, args): - """ generated source for method main """ - ll = DoublyCircularLinkedList() - ll.addHead(1) - ll.addHead(2) - ll.addHead(3) - ll.addHead(1) - ll.addHead(2) - ll.addHead(3) - print ll.size() - ll.printList() - -if __name__ == '__main__': - import sys - DoublyCircularLinkedList.main(sys.argv) \ No newline at end of file +ll = DoublyCircularLinkedList() +ll.addHead(1) +ll.addHead(2) +ll.addHead(3) +ll.addHead(1) +ll.addHead(2) +ll.addHead(3) +print ll.size() +ll.printList() diff --git a/LinkedList/DoublyLinkedList.py b/LinkedList/DoublyLinkedList.py index 33ed3b5..e1d365a 100755 --- a/LinkedList/DoublyLinkedList.py +++ b/LinkedList/DoublyLinkedList.py @@ -173,40 +173,36 @@ def copyList(self): curr = curr.next return dll -class DoublyLinkedListDemo(object): - @classmethod - def main(cls, args): - ll = DoublyLinkedList() - #======================================================================= - # ll.addHead(1) - # ll.addHead(2) - # ll.addHead(3) - # ll.addHead(4) - # ll.addHead(5) - # ll.addHead(6) - # ll.printList() - # ll.removeHead() - # ll.removeHead() - # ll.removeHead() - # ll.removeHead() - # ll.removeHead() - # ll.printList() - # ll.freeList() - # ll.printList() - #======================================================================= - ll.addHead(11) - ll.addHead(21) - ll.addHead(31) - ll.addHead(41) - ll.addHead(51) - ll.addHead(61) - ll.printList() - ll2 = ll.copyList() - ll2.printList() - ll3 = ll.copyListReversed() - ll3.printList() - + + +ll = DoublyLinkedList() +#======================================================================= +# ll.addHead(1) +# ll.addHead(2) +# ll.addHead(3) +# ll.addHead(4) +# ll.addHead(5) +# ll.addHead(6) +# ll.printList() +# ll.removeHead() +# ll.removeHead() +# ll.removeHead() +# ll.removeHead() +# ll.removeHead() +# ll.printList() +# ll.freeList() +# ll.printList() +#======================================================================= +ll.addHead(11) +ll.addHead(21) +ll.addHead(31) +ll.addHead(41) +ll.addHead(51) +ll.addHead(61) +ll.printList() +ll2 = ll.copyList() +ll2.printList() +ll3 = ll.copyListReversed() +ll3.printList() -if __name__ == '__main__': - import sys - DoublyLinkedListDemo.main(sys.argv) + diff --git a/LinkedList/LinkedList.py b/LinkedList/LinkedList.py index b5a2c09..ff1c184 100755 --- a/LinkedList/LinkedList.py +++ b/LinkedList/LinkedList.py @@ -312,62 +312,56 @@ def removeLoop(self): secondPtr.next = None -class LinkedListDemo(object): - @classmethod - def main(cls, args): - ll = LinkedList() - ll.sortedInsert(1) - ll.sortedInsert(2) - ll.sortedInsert(3) - ll.sortedInsert(5) - ll.sortedInsert(0) - ll.printList() - ll.makeLoop() - print ll.loopDetect() - print ll.loopTypeDetect() - print ll.loopPointDetect().value - print ll.reverseListLoopDetect() - print ll.removeLoop() - ll.printList() - - #======================================================================= - # print ll.isEmpty() - #======================================================================= - #======================================================================= - # print ll.isEmpty() - # print ll.peek() - # print ll.removeHead() - # ll.printList() - #======================================================================= - #======================================================================= - # print ll.isPresent(5) - # print ll.isPresent(2) - # ll.removeDuplicate() - # print ll.isEmpty() - # ll.deleteNodes(3) - #======================================================================= - #======================================================================= - # ll.reverse() - # ll.printList() - # ll.reverseRecurse() - # ll.printList() - #======================================================================= - #======================================================================= - # ll3 = ll.CopyListReversed() - # ll3.printList() - # - # ll2 = ll.copyList() - # ll2.printList() - # print ll.findLength() - #======================================================================= - #======================================================================= - # print ll.nthNodeFromBegining(2) - # print ll.nthNodeFromEnd(2) - # print ll.nthNodeFromEnd2(2) - #======================================================================= - - - -if __name__ == '__main__': - import sys - LinkedListDemo.main(sys.argv) \ No newline at end of file + +ll = LinkedList() +ll.sortedInsert(1) +ll.sortedInsert(2) +ll.sortedInsert(3) +ll.sortedInsert(5) +ll.sortedInsert(0) +ll.printList() +ll.makeLoop() +print ll.loopDetect() +print ll.loopTypeDetect() +print ll.loopPointDetect().value +print ll.reverseListLoopDetect() +print ll.removeLoop() +ll.printList() + +#======================================================================= +# print ll.isEmpty() +#======================================================================= +#======================================================================= +# print ll.isEmpty() +# print ll.peek() +# print ll.removeHead() +# ll.printList() +#======================================================================= +#======================================================================= +# print ll.isPresent(5) +# print ll.isPresent(2) +# ll.removeDuplicate() +# print ll.isEmpty() +# ll.deleteNodes(3) +#======================================================================= +#======================================================================= +# ll.reverse() +# ll.printList() +# ll.reverseRecurse() +# ll.printList() +#======================================================================= +#======================================================================= +# ll3 = ll.CopyListReversed() +# ll3.printList() +# +# ll2 = ll.copyList() +# ll2.printList() +# print ll.findLength() +#======================================================================= +#======================================================================= +# print ll.nthNodeFromBegining(2) +# print ll.nthNodeFromEnd(2) +# print ll.nthNodeFromEnd2(2) +#======================================================================= + + diff --git a/Queue/QueueArr.py b/Queue/QueueArr.py index b4616e0..07f78c9 100755 --- a/Queue/QueueArr.py +++ b/Queue/QueueArr.py @@ -22,18 +22,13 @@ def size(self): def printQueue(self): print self.data - @classmethod - def main(cls, args): - que = Queue() - i = 0 - while i < 20: - que.add(i) - i += 1 - i = 0 - while i < 22: - print que.remove() - i += 1 -if __name__ == '__main__': - import sys - Queue.main(sys.argv) \ No newline at end of file +que = Queue() +i = 0 +while i < 20: + que.add(i) + i += 1 +i = 0 +while i < 22: + print que.remove() + i += 1 diff --git a/Queue/QueueList.py b/Queue/QueueList.py index a78680b..2775152 100755 --- a/Queue/QueueList.py +++ b/Queue/QueueList.py @@ -45,19 +45,14 @@ def printList(self): print temp.value, temp = temp.next - @classmethod - def main(cls, args): - q = Queue() - i = 1 - while i <= 100: - q.add(i) - i += 1 - i = 1 - while i <= 50: - q.remove() - i += 1 - q.printList() - -if __name__ == '__main__': - import sys - Queue.main(sys.argv) \ No newline at end of file + +q = Queue() +i = 1 +while i <= 100: + q.add(i) + i += 1 +i = 1 +while i <= 50: + q.remove() + i += 1 +q.printList() diff --git a/Queue/QueueUsingStack.py b/Queue/QueueUsingStack.py index e0b2805..50856fe 100755 --- a/Queue/QueueUsingStack.py +++ b/Queue/QueueUsingStack.py @@ -16,24 +16,18 @@ def remove(self): self.stk2.append(value) return self.stk2.pop() - @classmethod - def main(cls, args): - que = QueueUsingStack() - que.add(1) - print que.remove() - - que.add(11) - que.add(111) - print que.remove() - que.add(2) - que.add(21) - que.add(211) - print que.remove() - print que.remove() - print que.remove() - print que.remove() - print que.remove() +que = QueueUsingStack() +que.add(1) +print que.remove() -if __name__ == '__main__': - import sys - QueueUsingStack.main(sys.argv) \ No newline at end of file +que.add(11) +que.add(111) +print que.remove() +que.add(2) +que.add(21) +que.add(211) +print que.remove() +print que.remove() +print que.remove() +print que.remove() +print que.remove() diff --git a/Searching/Searching.py b/Searching/Searching.py index 327488a..eba2862 100755 --- a/Searching/Searching.py +++ b/Searching/Searching.py @@ -1,827 +1,842 @@ #!/usr/bin/env python -""" Source for module Searching """ - -class Searching: - """ Source for class Searching """ - def __init__(self): - """ Source for method __init__ """ - - @classmethod - def main1(cls, args): - first = [1, 3, 5, 7, 9, 25, 30] - s = Searching() - print s.linearSearchSorted(first, 7, 8) - - def linearSearchUnsorted(self, arr, size, value): - i = 0 - while i < size: - if value == arr[i]: - return True - i += 1 - return False - def linearSearchSorted(self, arr, size, value): - i = 0 - while i < size: - if value == arr[i]: - return True - elif value < arr[i]: - return False - i += 1 - return False - - @classmethod - def main2(cls, args): - first = [1, 3, 5, 7, 9, 25, 30] - s = Searching() - print s.BinarySearchRecursive(first, 3) - - # Binary Search Algorithm - Iterative Way - def Binarysearch(self, arr, size, value): - low = 0 - high = size - 1 - - while low <= high: - mid = (low + high) / 2 - if arr[mid] == value: - return True - elif arr[mid] < value: - low = mid + 1 - else: - high = mid - 1 - return False - def BinarySearchRecursive(self, arr, value): - return self.BinarySearchRecursiveUtil(arr, 0, len(arr) - 1, value) +def linearSearchUnsorted(arr, size, value): + i = 0 + while i < size: + if value == arr[i]: + return True + i += 1 + return False - # Binary Search Algorithm - Recursive Way - def BinarySearchRecursiveUtil(self, arr, low, high, value): - if low > high: + +def linearSearchSorted(arr, size, value): + i = 0 + while i < size: + if value == arr[i]: + return True + elif value < arr[i]: return False + i += 1 + return False + +def main1(): + first = [1, 3, 5, 7, 9, 25, 30] + print linearSearchSorted(first, 7, 8) + + +# Binary Search Algorithm - Iterative Way +def Binarysearch(arr, size, value): + low = 0 + high = size - 1 + while low <= high: mid = (low + high) / 2 if arr[mid] == value: return True elif arr[mid] < value: - return self.BinarySearchRecursiveUtil(arr, mid + 1, high, value) + low = mid + 1 else: - return self.BinarySearchRecursiveUtil(arr, low, mid - 1, value) - - @classmethod - def main3(cls, args): - first = [1, 3, 5, 3, 9, 1, 30] - s = Searching() - s.printRepeating(first) - s.printRepeating2(first) - s.printRepeating3(first) - s.printRepeating4(first, 50) - - - def printRepeating(self, arr): - size = len(arr) - i = 0 - print " Repeating elements :: ", - while i < size: - j = i + 1 - while j < size: - if arr[i] == arr[j]: - print arr[i], - j += 1 - i += 1 + high = mid - 1 + return False - def printRepeating2(self, arr): - size = len(arr) - i = 0 - arr.sort() - print " Repeating elements are :: ", - while i < size: - if arr[i] == arr[i - 1]: - print arr[i], - i += 1 - def printRepeating3(self, arr): - size = len(arr) - hs = set() - i = 0 - print " Repeating elements are ::", - while i < size: - if arr[i] in hs: - print arr[i], - else: - hs.add(arr[i]) - i += 1 +def BinarySearchRecursive(arr, value): + return BinarySearchRecursiveUtil(arr, 0, len(arr) - 1, value) - def printRepeating4(self, arr, valrange): - size = len(arr) - count = [0] * valrange - i = 0 - print " Repeating elements are :: ", - while i < size: - if count[arr[i]] == 1: - print arr[i], - else: - count[arr[i]] += 1 - i += 1 - - @classmethod - def main4(cls, args): - first = [1, 30, 5, 13, 9, 31, 5] - s = Searching() - print s.getMax(first) - print s.getMax2(first) - print s.getMax3(first, 50) - - def getMax(self, arr): - size = len(arr) - maxval = arr[0] - count = 1 - maxCount = 1 - i = 0 - while i < size: - j = i + 1 - count = 1 - while j < size: - if arr[i] == arr[j]: - count += 1 - j += 1 - if count > maxCount: - maxval = arr[i] - maxCount = count - i += 1 - return maxval - - def getMax2(self, arr): - size = len(arr) - maximum = arr[0] - maxCount = 1 - curr = arr[0] - currCount = 1 - arr.sort() - i = 0 - while i < size: - if arr[i] == arr[i - 1]: - currCount += 1 - else: - currCount = 1 - curr = arr[i] - if currCount > maxCount: - maxCount = currCount - maximum = curr - i += 1 - return maximum +# Binary Search Algorithm - Recursive Way +def BinarySearchRecursiveUtil(arr, low, high, value): + if low > high: + return False + mid = (low + high) / 2 + if arr[mid] == value: + return True + elif arr[mid] < value: + return BinarySearchRecursiveUtil(arr, mid + 1, high, value) + else: + return BinarySearchRecursiveUtil(arr, low, mid - 1, value) - def getMax3(self, arr, valuerange): - size = len(arr) - maximum = arr[0] - maxCount = 1 - count = [0] * valuerange - i = int() - while i < size: - count[arr[i]] += 1 - if count[arr[i]] > maxCount: - maxCount = count[arr[i]] - maximum = arr[i] - i += 1 - return maximum - @classmethod - def main5(cls, args): - first = [1, 5, 5, 13, 5, 31, 5] - s = Searching() - print s.getMajority(first) - print s.getMajority2(first) - print s.getMajority3(first) - - def getMajority(self, arr): - size = len(arr) - maximum = 0 - count = 0 - maxCount = 0 - i = 0 - while i < size: - j = i + 1 - while j < size: - if arr[i] == arr[j]: - count += 1 - j += 1 - if count > maxCount: - maximum = arr[i] - maxCount = count - i += 1 - if maxCount > size / 2: - return maximum +def main2(): + first = [1, 3, 5, 7, 9, 25, 30] + print BinarySearchRecursive(first, 3) + + +def printRepeating(arr): + size = len(arr) + i = 0 + print " Repeating elements :: ", + while i < size: + j = i + 1 + while j < size: + if arr[i] == arr[j]: + print arr[i], + j += 1 + i += 1 + + +def printRepeating2(arr): + size = len(arr) + i = 0 + arr.sort() + print " Repeating elements are :: ", + while i < size: + if arr[i] == arr[i - 1]: + print arr[i], + i += 1 + + +def printRepeating3(arr): + size = len(arr) + hs = set() + i = 0 + print " Repeating elements are ::", + while i < size: + if arr[i] in hs: + print arr[i], else: - return sys.maxint # can also raised exception. - - def getMajority2(self, arr): - size = len(arr) - majIndex = size / 2 - i = 0 - arr.sort() - candidate = arr[majIndex] - count = 1 - while i < size: - if arr[i] == candidate: - count += 1 - i += 1 - if count > size / 2: - return arr[majIndex] + hs.add(arr[i]) + i += 1 + + +def printRepeating4(arr, valrange): + size = len(arr) + count = [0] * valrange + i = 0 + print " Repeating elements are :: ", + while i < size: + if count[arr[i]] == 1: + print arr[i], else: - return sys.maxint # can also raised exception. + count[arr[i]] += 1 + i += 1 + - def getMajority3(self, arr): - size = len(arr) - majIndex = 0 +def main3(): + first = [1, 3, 5, 3, 9, 1, 30] + printRepeating(first) + printRepeating2(first) + printRepeating3(first) + printRepeating4(first, 50) + + +def getMax(arr): + size = len(arr) + maxval = arr[0] + count = 1 + maxCount = 1 + i = 0 + while i < size: + j = i + 1 count = 1 - i = 1 - while i < size: - if arr[majIndex] == arr[i]: + while j < size: + if arr[i] == arr[j]: count += 1 - else: - count -= 1 - if count == 0: - majIndex = i - count = 1 - i += 1 - candidate = arr[majIndex] - count = 0 - i = 0 - while i < size: - if arr[i] == candidate: + j += 1 + if count > maxCount: + maxval = arr[i] + maxCount = count + i += 1 + return maxval + + +def getMax2(arr): + size = len(arr) + maximum = arr[0] + maxCount = 1 + curr = arr[0] + currCount = 1 + arr.sort() + i = 0 + while i < size: + if arr[i] == arr[i - 1]: + currCount += 1 + else: + currCount = 1 + curr = arr[i] + if currCount > maxCount: + maxCount = currCount + maximum = curr + i += 1 + return maximum + + +def getMax3(arr, valuerange): + size = len(arr) + maximum = arr[0] + maxCount = 1 + count = [0] * valuerange + i = int() + while i < size: + count[arr[i]] += 1 + if count[arr[i]] > maxCount: + maxCount = count[arr[i]] + maximum = arr[i] + i += 1 + return maximum + + +def main4(): + first = [1, 30, 5, 13, 9, 31, 5] + print getMax(first) + print getMax2(first) + print getMax3(first, 50) + + +def getMajority(arr): + size = len(arr) + maximum = 0 + count = 0 + maxCount = 0 + i = 0 + while i < size: + j = i + 1 + while j < size: + if arr[i] == arr[j]: count += 1 - i += 1 - if count > size / 2: - return arr[majIndex] + j += 1 + if count > maxCount: + maximum = arr[i] + maxCount = count + i += 1 + if maxCount > size / 2: + return maximum + else: + return symaxint # can also raised exception. + + +def getMajority2(arr): + size = len(arr) + majIndex = size / 2 + i = 0 + arr.sort() + candidate = arr[majIndex] + count = 1 + while i < size: + if arr[i] == candidate: + count += 1 + i += 1 + if count > size / 2: + return arr[majIndex] + else: + return symaxint # can also raised exception. + + +def getMajority3(arr): + size = len(arr) + majIndex = 0 + count = 1 + i = 1 + while i < size: + if arr[majIndex] == arr[i]: + count += 1 else: - return sys.maxint # can also raised exception. - - @classmethod - def main6(cls, args): - first = [1, 5, 4, 3, 2, 7, 8, 9, 10] - s = Searching() - # print s.findMissingNumber(first, 9) - print s.findMissingNumber3(first, 9) - - def findMissingNumber(self, arr, upperRange): - size = len(arr) - i = 1 - found = 0 - while i <= upperRange: - found = 0 - j = 0 - while j < size: - if arr[j] == i: - found = 1 - break - j += 1 - if found == 0: - return i - i += 1 - return sys.maxint - - def findMissingNumber2(self, arr, upperRange): - size = len(arr) - i = 1 - xorSum = 0 - while i <= upperRange: - xorSum ^= i - i += 1 - i = 0 - while i < size: - xorSum ^= arr[i] - i += 1 - return xorSum - - def findMissingNumber3(self, arr, upperRange): - size = len(arr) - mSet = set() - i = 0 - while i < size: - mSet.add(arr[i]) - i += 1 - i = 1 - while i <= upperRange: - if (i in mSet) == False: - return i - i += 1 - return sys.maxint - - - - @classmethod - def main7(cls, args): - first = [1, 5, 4, 3, 2, 7, 8, 9, 6] - s = Searching() - print s.FindPair(first, 8) - print s.FindPair2(first, 8) - print s.FindPair3(first, 8) - - - def FindPair(self, arr, value): - size = len(arr) - i = 0 - while i < size: - j = i + 1 - while j < size: - if (arr[i] + arr[j]) == value: - print "The pair is::", arr[i], "&" , arr[j] - return True - j += 1 - i += 1 - return False + count -= 1 + if count == 0: + majIndex = i + count = 1 + i += 1 + candidate = arr[majIndex] + count = 0 + i = 0 + while i < size: + if arr[i] == candidate: + count += 1 + i += 1 + if count > size / 2: + return arr[majIndex] + else: + return symaxint # can also raised exception. - def FindPair2(self, arr, value): - size = len(arr) - first = 0 - second = size - 1 - arr.sort() - while first < second: - curr = arr[first] + arr[second] - if curr == value: - print "The pair is::", arr[first], "&", arr[second] - return True - elif curr < value: - first += 1 - else: - second -= 1 - return False - def FindPair3(self, arr, value): - size = len(arr) - hs = set() - i = int() - while i < size: - if (value - arr[i]) in hs: - print "The pair is::", arr[i] , "&" , (value - arr[i]) +def main5(): + first = [1, 5, 5, 13, 5, 31, 5] + print getMajority(first) + print getMajority2(first) + print getMajority3(first) + + +def findMissingNumber(arr, upperRange): + size = len(arr) + i = 1 + found = 0 + while i <= upperRange: + found = 0 + j = 0 + while j < size: + if arr[j] == i: + found = 1 + break + j += 1 + if found == 0: + return i + i += 1 + return symaxint + + +def findMissingNumber2(arr, upperRange): + size = len(arr) + i = 1 + xorSum = 0 + while i <= upperRange: + xorSum ^= i + i += 1 + i = 0 + while i < size: + xorSum ^= arr[i] + i += 1 + return xorSum + + +def findMissingNumber3(arr, upperRange): + size = len(arr) + mSet = set() + i = 0 + while i < size: + mSet.add(arr[i]) + i += 1 + i = 1 + while i <= upperRange: + if (i in mSet) == False: + return i + i += 1 + return symaxint + + +def main6(): + first = [1, 5, 4, 3, 2, 7, 8, 9, 10] + # print findMissingNumber(first, 9) + print findMissingNumber3(first, 9) + + +def FindPair(arr, value): + size = len(arr) + i = 0 + while i < size: + j = i + 1 + while j < size: + if (arr[i] + arr[j]) == value: + print "The pair is::", arr[i], "&" , arr[j] return True - hs.add(arr[i]) - i += 1 - return False + j += 1 + i += 1 + return False + + +def FindPair2(arr, value): + size = len(arr) + first = 0 + second = size - 1 + arr.sort() + while first < second: + curr = arr[first] + arr[second] + if curr == value: + print "The pair is::", arr[first], "&", arr[second] + return True + elif curr < value: + first += 1 + else: + second -= 1 + return False - @classmethod - def main8(cls, args): - first = [1, 5, -10, 3, 2, -6, 8, 9, 6] - s = Searching() - print s.minabsSumPair2(first) - print s.minabsSumPair(first) - # print s.minabsSumPair(first) - - def minabsSumPair(self, arr): - size = len(arr) - if size < 2: - print "Invalid Input" - return - minFirst = 0 - minSecond = 1 - i = 0 - minSum = abs(arr[0] + arr[1]) - while i < size - 1: - j = i + 1 - while j < size: - currsum = abs(arr[i] + arr[j]) - if currsum < minSum: - minSum = currsum - minFirst = i - minSecond = j - j += 1 - i += 1 - print " The two elements with minimum sum are : ", arr[minFirst], "&", arr[minSecond] - - def minabsSumPair2(self, arr): - size = len(arr) - if size < 2: - print "Invalid Input" - return - arr.sort() - minFirst = 0 - minSecond = size - 1 - minSum = abs(arr[minFirst] + arr[minSecond]) - l = 0 - r = size - 1 - while l < r: - currsum = (arr[l] + arr[r]) - if abs(currsum) < minSum: +def FindPair3(arr, value): + size = len(arr) + hs = set() + i = int() + while i < size: + if (value - arr[i]) in hs: + print "The pair is::", arr[i] , "&" , (value - arr[i]) + return True + hs.add(arr[i]) + i += 1 + return False + + +def main7(): + first = [1, 5, 4, 3, 2, 7, 8, 9, 6] + print FindPair(first, 8) + print FindPair2(first, 8) + print FindPair3(first, 8) + + +def minabsSumPair(arr): + size = len(arr) + if size < 2: + print "Invalid Input" + return + minFirst = 0 + minSecond = 1 + i = 0 + minSum = abs(arr[0] + arr[1]) + while i < size - 1: + j = i + 1 + while j < size: + currsum = abs(arr[i] + arr[j]) + if currsum < minSum: minSum = currsum - minFirst = l - minSecond = r - if currsum < 0: - l += 1 - elif currsum > 0: - r -= 1 - else: - break - print " The two elements with minimum sum are : ", arr[minFirst], "&" , arr[minSecond] + minFirst = i + minSecond = j + j += 1 + i += 1 + print " The two elements with minimum sum are : ", arr[minFirst], "&", arr[minSecond] + + +def minabsSumPair2(arr): + size = len(arr) + if size < 2: + print "Invalid Input" + return + arr.sort() + minFirst = 0 + minSecond = size - 1 + minSum = abs(arr[minFirst] + arr[minSecond]) + l = 0 + r = size - 1 + while l < r: + currsum = (arr[l] + arr[r]) + if abs(currsum) < minSum: + minSum = currsum + minFirst = l + minSecond = r + if currsum < 0: + l += 1 + elif currsum > 0: + r -= 1 + else: + break + print " The two elements with minimum sum are : ", arr[minFirst], "&" , arr[minSecond] + +def main8(): + first = [1, 5, -10, 3, 2, -6, 8, 9, 6] + print minabsSumPair2(first) + print minabsSumPair(first) + # print minabsSumPair(first) - @classmethod - def main9(cls, args): - first = [1, 5, 10, 13, 20, 30, 8, 7, 6] - s = Searching() - print s.SearchBotinicArrayMax(first) - print s.SearchBitonicArray(first, 32) - # print s.minabsSumPair(first) - def SearchBotinicArrayMax(self, arr): - size = len(arr) - start = 0 - end = size - 1 +def SearchBotinicArrayMax(arr): + size = len(arr) + start = 0 + end = size - 1 + mid = (start + end) / 2 + maximaFound = 0 + if size < 3: + print "error" + return 0 + while start <= end: mid = (start + end) / 2 - maximaFound = 0 - if size < 3: - print "error" - return 0 - while start <= end: - mid = (start + end) / 2 - if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]: - maximaFound = 1 - break - elif arr[mid - 1] < arr[mid] and arr[mid] < arr[mid + 1]: - start = mid + 1 - elif arr[mid - 1] > arr[mid] and arr[mid] > arr[mid + 1]: - end = mid - 1 - else: - break - if maximaFound == 0: - print "error" - return sys.maxint - return arr[mid] - - def SearchBitonicArray(self, arr, key): - size = len(arr) - maxval = self.FindMaxBitonicIndex(arr, size) - k = self.BinarySearch(arr, 0, maxval, key, True) - if k == True: - return True + if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]: + maximaFound = 1 + break + elif arr[mid - 1] < arr[mid] and arr[mid] < arr[mid + 1]: + start = mid + 1 + elif arr[mid - 1] > arr[mid] and arr[mid] > arr[mid + 1]: + end = mid - 1 else: - return self.BinarySearch(arr, maxval + 1, size - 1, key, False) - - def FindMaxBitonicIndex(self, arr, size): - start = 0 - end = size - 1 - if size < 3: - print "error" - return -1 - while start <= end: - mid = (start + end) / 2 - if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]: - return mid - elif arr[mid - 1] < arr[mid] and arr[mid] < arr[mid + 1]: - start = mid + 1 - elif arr[mid - 1] > arr[mid] and arr[mid] > arr[mid + 1]: - end = mid - 1 - else: - break + break + if maximaFound == 0: print "error" - return -1 + return symaxint + return arr[mid] - def BinarySearch(self, arr, start, end, key, isInc): - if end < start: - return False - mid = (start + end) / 2 - if key == arr[mid]: - return True - if isInc != False and key < arr[mid] or isInc == False and key > arr[mid]: - return self.BinarySearch(arr, start, mid - 1, key, isInc) - else: - return self.BinarySearch(arr, mid + 1, end, key, isInc) - - @classmethod - def main10(cls, args): - first = [1, 5, 10, 13, 20, 30, 8, 7, 6] - s = Searching() - print s.findKeyCount(first, 6) - print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def findKeyCount(self, arr, key): - size = len(arr) - i = 0 - count = 0 - while i < size: - if arr[i] == key: - count += 1 - i += 1 - return count - - def findKeyCount2(self, arr, key): - size = len(arr) - firstIndex = self.findFirstIndex(arr, 0, size - 1, key) - lastIndex = self.findLastIndex(arr, 0, size - 1, key) - return (lastIndex - firstIndex + 1) - - @classmethod - def main11(cls, args): - first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - s = Searching() - print s.findKeyCount(first, 6) - print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def findFirstIndex(self, arr, start, end, key): - if end < start: - return -1 - mid = (start + end) / 2 - if key == arr[mid] and (mid == start or arr[mid - 1] != key): - return mid - if key <= arr[mid]: - return self.findFirstIndex(arr, start, mid - 1, key) - else: - return self.findFirstIndex(arr, mid + 1, end, key) - def findLastIndex(self, arr, start, end, key): - if end < start: - return -1 +def SearchBitonicArray(arr, key): + size = len(arr) + maxval = FindMaxBitonicIndex(arr, size) + k = BinarySearch(arr, 0, maxval, key, True) + if k == True: + return True + else: + return BinarySearch(arr, maxval + 1, size - 1, key, False) + + +def FindMaxBitonicIndex(arr, size): + start = 0 + end = size - 1 + if size < 3: + print "error" + return -1 + while start <= end: mid = (start + end) / 2 - if key == arr[mid] and (mid == end or arr[mid + 1] != key): + if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]: return mid - if key < arr[mid]: - return self.findLastIndex(arr, start, mid - 1, key) + elif arr[mid - 1] < arr[mid] and arr[mid] < arr[mid + 1]: + start = mid + 1 + elif arr[mid - 1] > arr[mid] and arr[mid] > arr[mid + 1]: + end = mid - 1 else: - return self.findLastIndex(arr, mid + 1, end, key) - - @classmethod - def main12(cls, args): - first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - s = Searching() - print s.seperateEvenAndOdd(first) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - - def swap(self, arr, first, second): - temp = arr[first] - arr[first] = arr[second] - arr[second] = temp - - def seperateEvenAndOdd(self, arr): - size = len(arr) - left = 0 - right = size - 1 - while left < right: - if arr[left] % 2 == 0: - left += 1 - elif arr[right] % 2 == 1: - right -= 1 - else: - self.swap(arr, left, right) - left += 1 - right -= 1 - return arr - - @classmethod - def main(cls, args): - first = [10, 150, 6, 67, 61, 16, 86, 6, 67, 78, 150, -3, 28, 143 ] - s = Searching() - print s.maxProfit(first) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def maxProfit(self, stocks): - size = len(stocks) - buy = 0 - sell = 0 - curMin = 0 - currProfit = 0 - maxProfit = 0 - i = 0 - while i < size: - if stocks[i] < stocks[curMin]: - curMin = i - currProfit = stocks[i] - stocks[curMin] - if currProfit > maxProfit: - buy = curMin - sell = i - maxProfit = currProfit - i += 1 - print "Purchase day is - ", buy , " at price " , stocks[buy] - print "Sell day is - " , sell , " at price " , stocks[sell] - - @classmethod - def main14(cls, args): - # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] - first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - second = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - s = Searching() - print s.findMedian(first, second) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def getMedian(self, arr): - size = len(arr) - arr.sort() - return arr[size / 2] - - def findMedian(self, arrFirst, arrSecond): - sizeFirst = len(arrFirst) - sizeSecond = len(arrSecond) - medianIndex = ((sizeFirst + sizeSecond) + (sizeFirst + sizeSecond) % 2) / 2 - i = 0 - j = 0 - count = 0 - while count < medianIndex - 1: - if i < sizeFirst - 1 and arrFirst[i] < arrSecond[j]: - i += 1 - else: - j += 1 + break + print "error" + return -1 + +def main9(): + first = [1, 5, 10, 13, 20, 30, 8, 7, 6] + + print SearchBotinicArrayMax(first) + print SearchBitonicArray(first, 32) + # print minabsSumPair(first) + +def BinarySearch(arr, start, end, key, isInc): + if end < start: + return False + mid = (start + end) / 2 + if key == arr[mid]: + return True + if isInc != False and key < arr[mid] or isInc == False and key > arr[mid]: + return BinarySearch(arr, start, mid - 1, key, isInc) + else: + return BinarySearch(arr, mid + 1, end, key, isInc) + + + + +def findKeyCount(arr, key): + size = len(arr) + i = 0 + count = 0 + while i < size: + if arr[i] == key: count += 1 - if arrFirst[i] < arrSecond[j]: - return arrFirst[i] - else: - return arrSecond[j] - - @classmethod - def min(cls, a, b): - return b if a > b else a - - @classmethod - def max(cls, a, b): - return b if a < b else a - - @classmethod - def main15(cls, args): - # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] - # first = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] - # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] - first = "000000001111" - s = Searching() - print s.BinarySearch01(first) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def BinarySearch01(self, arr): - size = len(arr) - if size == 1 and arr[0] == '1': - return 0 - return self.BinarySearch01Util(arr, 0, size - 1) - - def BinarySearch01Util(self, arr, start, end): - if end < start: - return -1 - mid = (start + end) / 2 - if '1' == arr[mid] and '0' == arr[mid - 1]: - return mid - if '0' == arr[mid]: - return self.BinarySearch01Util(arr, mid + 1, end) - else: - return self.BinarySearch01Util(arr, start, mid - 1) - - @classmethod - def main16(cls, args): - # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] - # - first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] - - s = Searching() - print s.BinarySearchRotateArray(first, 20) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def BinarySearchRotateArray(self, arr, key): - size = len(arr) - return self.BinarySearchRotateArrayUtil(arr, 0, size - 1, key) - - def BinarySearchRotateArrayUtil(self, arr, start, end, key): - if end < start: - return False - mid = (start + end) / 2 - if key == arr[mid]: - return True - if arr[mid] > arr[start]: - if arr[start] <= key and key < arr[mid]: - return self.BinarySearchRotateArrayUtil(arr, start, mid - 1, key) - else: - return self.BinarySearchRotateArrayUtil(arr, mid + 1, end, key) + i += 1 + return count + +def findFirstIndex(arr, start, end, key): + if end < start: + return -1 + mid = (start + end) / 2 + if key == arr[mid] and (mid == start or arr[mid - 1] != key): + return mid + if key <= arr[mid]: + return findFirstIndex(arr, start, mid - 1, key) + else: + return findFirstIndex(arr, mid + 1, end, key) + +def findLastIndex(arr, start, end, key): + if end < start: + return -1 + mid = (start + end) / 2 + if key == arr[mid] and (mid == end or arr[mid + 1] != key): + return mid + if key < arr[mid]: + return findLastIndex(arr, start, mid - 1, key) + else: + return findLastIndex(arr, mid + 1, end, key) +def findKeyCount2(arr, key): + size = len(arr) + firstIndex = findFirstIndex(arr, 0, size - 1, key) + lastIndex = findLastIndex(arr, 0, size - 1, key) + return (lastIndex - firstIndex + 1) + +def main10(): + first = [1, 5, 10, 13, 20, 30, 8, 7, 6] + + print findKeyCount(first, 6) + print findKeyCount2(first, 6) + # print minabsSumPair(first) + +def main11(): + first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] + + print findKeyCount(first, 6) + print findKeyCount2(first, 6) + # print minabsSumPair(first) + + + +def swap(arr, first, second): + temp = arr[first] + arr[first] = arr[second] + arr[second] = temp + +def seperateEvenAndOdd(arr): + size = len(arr) + left = 0 + right = size - 1 + while left < right: + if arr[left] % 2 == 0: + left += 1 + elif arr[right] % 2 == 1: + right -= 1 else: - if arr[mid] < key and key <= arr[end]: - return self.BinarySearchRotateArrayUtil(arr, mid + 1, end, key) - else: - return self.BinarySearchRotateArrayUtil(arr, start, mid - 1, key) + swap(arr, left, right) + left += 1 + right -= 1 + return arr + +def main12(): + first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] - @classmethod - def main17(cls, args): - # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] - # - first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 34, 20, 30 ] - # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] - s = Searching() - print s.FirstRepeated(first) - # print s.findKeyCount2(first, 6) - # print s.minabsSumPair(first) - - def FirstRepeated(self, arr): - size = len(arr) - i = 0 - while i < size: - j = i + 1 - while j < size: - if arr[i] == arr[j]: - return arr[i] - j += 1 - i += 1 - return sys.maxint # can raise exception. + print seperateEvenAndOdd(first) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) - @classmethod - def main18(cls, args): - - - # [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] - # - # first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 34, 20, 30 ] - # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] - s = Searching() - print s.transformArrayAB1("aaaabbbb") - - def transformArrayAB1(self, strval): - arr = list(strval) - size = len(arr) - N = size / 2 - i = 1 - while i < N: - j = 0 - while j < i: - self.swap(arr, N - i + 2 * j, N - i + 2 * j + 1) - j += 1 +def main13(): + first = [10, 150, 6, 67, 61, 16, 86, 6, 67, 78, 150, -3, 28, 143 ] + + print maxProfit(first) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) + +def maxProfit(stocks): + size = len(stocks) + buy = 0 + sell = 0 + curMin = 0 + currProfit = 0 + maxProfit = 0 + i = 0 + while i < size: + if stocks[i] < stocks[curMin]: + curMin = i + currProfit = stocks[i] - stocks[curMin] + if currProfit > maxProfit: + buy = curMin + sell = i + maxProfit = currProfit + i += 1 + print "Purchase day is - ", buy , " at price " , stocks[buy] + print "Sell day is - " , sell , " at price " , stocks[sell] + + +def main14(): + # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] + first = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] + second = [1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] + + print findMedian(first, second) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) + +def getMedian(arr): + size = len(arr) + arr.sort() + return arr[size / 2] + +def findMedian(arrFirst, arrSecond): + sizeFirst = len(arrFirst) + sizeSecond = len(arrSecond) + medianIndex = ((sizeFirst + sizeSecond) + (sizeFirst + sizeSecond) % 2) / 2 + i = 0 + j = 0 + count = 0 + while count < medianIndex - 1: + if i < sizeFirst - 1 and arrFirst[i] < arrSecond[j]: i += 1 - return "".join(arr) + else: + j += 1 + count += 1 + if arrFirst[i] < arrSecond[j]: + return arrFirst[i] + else: + return arrSecond[j] - @classmethod - def main19(cls, args): - s = Searching() - print s.checkPermutation2("aaaabbbb", "bbaaaabb") - def checkPermutation(self, str1, str2): - array1 = list(str1) - array2 = list(str2) - - size1 = len(array1) - size2 = len(array2) - if size1 != size2: - return False - array1.sort() - array2.sort() - i = 0 - while i < size1: - if array1[i] != array2[i]: - return False - i += 1 - return True +def min(a, b): + return b if a > b else a - def checkPermutation2(self, array1, array2): - size1 = len(array1) - size2 = len(array2) - if size1 != size2: - return False - al = [] - i = 0 - while i < size1: - al.append(array1[i]) - i += 1 - i = 0 - while i < size2: - if al.count(array2[i]) == 0: - return False - al.remove(array2[i]) - i += 1 + +def max(a, b): + return b if a < b else a + + +def main15(): + # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] + # first = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] + # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] + first = "000000001111" + print BinarySearch01(first) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) + + +def BinarySearch01(arr): + size = len(arr) + if size == 1 and arr[0] == '1': + return 0 + return BinarySearch01Util(arr, 0, size - 1) + + +def BinarySearch01Util(arr, start, end): + if end < start: + return -1 + mid = (start + end) / 2 + if '1' == arr[mid] and '0' == arr[mid - 1]: + return mid + if '0' == arr[mid]: + return BinarySearch01Util(arr, mid + 1, end) + else: + return BinarySearch01Util(arr, start, mid - 1) + + +def main16(): + # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] + first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 13, 20, 30 ] + # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] + print BinarySearchRotateArray(first, 20) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) + + +def BinarySearchRotateArray(arr, key): + size = len(arr) + return BinarySearchRotateArrayUtil(arr, 0, size - 1, key) + + +def BinarySearchRotateArrayUtil(arr, start, end, key): + if end < start: + return False + mid = (start + end) / 2 + if key == arr[mid]: return True + if arr[mid] > arr[start]: + if arr[start] <= key and key < arr[mid]: + return BinarySearchRotateArrayUtil(arr, start, mid - 1, key) + else: + return BinarySearchRotateArrayUtil(arr, mid + 1, end, key) + else: + if arr[mid] < key and key <= arr[end]: + return BinarySearchRotateArrayUtil(arr, mid + 1, end, key) + else: + return BinarySearchRotateArrayUtil(arr, start, mid - 1, key) + + + +def main17(): + # first = [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] + first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 34, 20, 30 ] + # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] + print FirstRepeated(first) + # print findKeyCount2(first, 6) + # print minabsSumPair(first) - @classmethod - def main20(cls, args): - s = Searching() - first = [1, 7, 6, 4, 8, 3, 8, 2, 6, 9] - print s.removeDuplicates(first) - def removeDuplicates(self, array): - size = len(array) +def FirstRepeated(arr): + size = len(arr) + i = 0 + while i < size: + j = i + 1 + while j < size: + if arr[i] == arr[j]: + return arr[i] + j += 1 + i += 1 + return symaxint # can raise exception. + + +def main18(): + # [10, 150, 6,67,61,16,86,6,67,78,150, -3, 28, 143 ] + # first = [34, 56, 77, 1, 5, 6, 6, 6, 6, 6, 6, 7, 8, 10, 34, 20, 30 ] + # second = [1, 5, 6,6,6,6,6,6,7,8,10, 13, 20, 30 ] + print transformArrayAB1("aaaabbbb") + + +def transformArrayAB1(strval): + arr = list(strval) + size = len(arr) + N = size / 2 + i = 1 + while i < N: j = 0 - i = int() - if size == 0: - return 0 - array.sort() - while i < size: - if array[i] != array[j]: - j += 1 - array[j] = array[i] - i += 1 - array[j:size - 1] = [] - return array - - def FindElementIn2DArray(self, arr, r, c, value): - row = 0 - column = c - 1 - while row < r and column >= 0: - if arr[row][column] == value: - return True - elif arr[row][column] > value: - column -= 1 - else: - row += 1 - return False + while j < i: + swap(arr, N - i + 2 * j, N - i + 2 * j + 1) + j += 1 + i += 1 + return "".join(arr) + +def main19(): + print checkPermutation2("aaaabbbb", "bbaaaabb") -if __name__ == '__main__': - import sys - Searching.main(sys.argv) +def checkPermutation(str1, str2): + array1 = list(str1) + array2 = list(str2) + size1 = len(array1) + size2 = len(array2) + if size1 != size2: + return False + array1.sort() + array2.sort() + i = 0 + while i < size1: + if array1[i] != array2[i]: + return False + i += 1 + return True + + +def checkPermutation2(array1, array2): + size1 = len(array1) + size2 = len(array2) + if size1 != size2: + return False + al = [] + i = 0 + while i < size1: + al.append(array1[i]) + i += 1 + i = 0 + while i < size2: + if al.count(array2[i]) == 0: + return False + al.remove(array2[i]) + i += 1 + return True + + +def main20(): + first = [1, 7, 6, 4, 8, 3, 8, 2, 6, 9] + print removeDuplicates(first) + + +def removeDuplicates(array): + size = len(array) + j = 0 + i = int() + if size == 0: + return 0 + array.sort() + while i < size: + if array[i] != array[j]: + j += 1 + array[j] = array[i] + i += 1 + array[j:size - 1] = [] + return array + + +def FindElementIn2DArray(arr, r, c, value): + row = 0 + column = c - 1 + while row < r and column >= 0: + if arr[row][column] == value: + return True + elif arr[row][column] > value: + column -= 1 + else: + row += 1 + return False + + +main1() +main2() +main3() +main4() +main5() +main6() +main7() +main8() +main9() +main10() +main11() +main12() +main13() +main14() +main15() +main16() +main17() +main18() +main19() +main20() diff --git a/Sorting/BubbleSort.py b/Sorting/BubbleSort.py index 7de226b..b75f6f5 100755 --- a/Sorting/BubbleSort.py +++ b/Sorting/BubbleSort.py @@ -1,52 +1,45 @@ #!/usr/bin/env python -class BubbleSort(object): - def __init__(self, array): - self.arr = array - self.sort2() - def less(self, value1, value2): - return value1 < value2 +def less(value1, value2): + return value1 < value2 - def more(self, value1, value2): - return value1 > value2 +def more(value1, value2): + return value1 > value2 - def sort(self): - size = len(self.arr) - i = 0 - while i < (size - 1): - j = 0 - while j < size - i - 1: - if self.more(self.arr[j], self.arr[j + 1]): - # Swapping - temp = self.arr[j] - self.arr[j] = self.arr[j + 1] - self.arr[j + 1] = temp - j += 1 - i += 1 +def BubbleSort(arr): + size = len(arr) + i = 0 + while i < (size - 1): + j = 0 + while j < size - i - 1: + if more(arr[j], arr[j + 1]): + # Swapping + temp = arr[j] + arr[j] = arr[j + 1] + arr[j + 1] = temp + j += 1 + i += 1 - def sort2(self): - size = len(self.arr) - swapped = 1 - i = 0 - while i < (size - 1) and swapped == 1: - swapped = 0 - j = 0 - while j < size - i - 1: - if self.more(self.arr[j], self.arr[j + 1]): - temp = self.arr[j] - self.arr[j] = self.arr[j + 1] - self.arr[j + 1] = temp - swapped = 1 - j += 1 - i += 1 +def BubbleSort2(arr): + size = len(arr) + swapped = 1 + i = 0 + while i < (size - 1) and swapped == 1: + swapped = 0 + j = 0 + while j < size - i - 1: + if more(arr[j], arr[j + 1]): + temp = arr[j] + arr[j] = arr[j + 1] + arr[j + 1] = temp + swapped = 1 + j += 1 + i += 1 -class BubbleSortDemo: - @classmethod - def main(cls, args): - array = [9, 1, 8, 2, 7, 3, 6, 4, 5] - BubbleSort(array) - print array -if __name__ == '__main__': - import sys - BubbleSortDemo.main(sys.argv) \ No newline at end of file +array = [9, 1, 8, 2, 7, 3, 6, 4, 5] +BubbleSort(array) +print array +array = [9, 1, 8, 2, 7, 3, 6, 4, 5] +BubbleSort2(array) +print array diff --git a/Sorting/BucketSort.py b/Sorting/BucketSort.py index 522db1f..c216d6e 100755 --- a/Sorting/BucketSort.py +++ b/Sorting/BucketSort.py @@ -1,33 +1,25 @@ #!/usr/bin/env python -class BucketSort(object): - def __init__(self, arr, lowerRange, upperRange): - self.array = arr - self.range = upperRange - lowerRange - self.lowerRange = lowerRange - size = len(self.array) - count = [0] * self.range - i = 0 - while i < size: - count[self.array[i] - self.lowerRange] += 1 - i += 1 - - j = 0 - i = 0 - while i < self.range: - while count[i] > 0: - self.array[j] = i + self.lowerRange - count[i] -= 1 - j += 1 - i += 1 - +def BucketSort(arr, lowerRange, upperRange): + array = arr + range = upperRange - lowerRange + lowerRange = lowerRange + size = len(array) + count = [0] * range + i = 0 + while i < size: + count[array[i] - lowerRange] += 1 + i += 1 + + j = 0 + i = 0 + while i < range: + while count[i] > 0: + array[j] = i + lowerRange + count[i] -= 1 + j += 1 + i += 1 + -class BucketSortDemo(object): - @classmethod - def main(cls, args): - array = [23, 24, 22, 21, 26, 25, 27, 28, 21, 21] - BucketSort(array, 20, 30) - print array - -if __name__ == '__main__': - import sys - BucketSortDemo.main(sys.argv) \ No newline at end of file +array = [23, 24, 22, 21, 26, 25, 27, 28, 21, 21] +BucketSort(array, 20, 30) +print array diff --git a/Sorting/InsertionSort.py b/Sorting/InsertionSort.py index 262fefe..349ea48 100755 --- a/Sorting/InsertionSort.py +++ b/Sorting/InsertionSort.py @@ -1,34 +1,21 @@ #!/usr/bin/env python -""" generated source for module InsertionSort """ -class InsertionSort(object): - def __init__(self, array): - self.arr = array - self.sort() +def more(value1, value2): + return value1 > value2 - def more(self, value1, value2): - return value1 > value2 +def InsertionSort(arr): + size = len(arr) + i = 1 + while i < size: + temp = arr[i] + j = i; + while j > 0 and more(arr[j - 1], temp): + arr[j] = arr[j - 1] + j -= 1 + arr[j] = temp + i += 1 - def sort(self): - size = len(self.arr) - i = 1 - while i < size: - temp = self.arr[i] - j = i; - while j > 0 and self.more(self.arr[j - 1], temp): - self.arr[j] = self.arr[j - 1] - j -= 1 - self.arr[j] = temp - i += 1 -class InsertionSortDemo(object): - @classmethod - def main(cls, args): - array = [9, 1, 8, 2, 7, 3, 6, 4, 5] - InsertionSort(array) - print array - - -if __name__ == '__main__': - import sys - InsertionSortDemo.main(sys.argv) +array = [9, 1, 8, 2, 7, 3, 6, 4, 5] +InsertionSort(array) +print array diff --git a/Sorting/MergeSort.py b/Sorting/MergeSort.py index a3794b1..3d2b646 100755 --- a/Sorting/MergeSort.py +++ b/Sorting/MergeSort.py @@ -1,60 +1,52 @@ #!/usr/bin/env python -class MergeSort(object): - def __init__(self, array): - self.arr = array - size = len(self.arr) - tempArray = [0] * size - self.mergeSrt(self.arr, tempArray, 0, size - 1) - - def mergeSrt(self, arr, tempArray, lowerIndex, upperIndex): - if lowerIndex >= upperIndex: - return - middleIndex = (lowerIndex + upperIndex) / 2 - self.mergeSrt(arr, tempArray, lowerIndex, middleIndex) - self.mergeSrt(arr, tempArray, middleIndex + 1, upperIndex) - self.merge(arr, tempArray, lowerIndex, middleIndex, upperIndex) +def MergeSort(array): + arr = array + size = len(arr) + tempArray = [0] * size + mergeSrt(arr, tempArray, 0, size - 1) - def merge(self, arr, tempArray, lowerIndex, middleIndex, upperIndex): - lowerStart = lowerIndex - lowerStop = middleIndex - upperStart = middleIndex + 1 - upperStop = upperIndex - count = lowerIndex - - while lowerStart <= lowerStop and upperStart <= upperStop: - if arr[lowerStart] < arr[upperStart]: - tempArray[count] = arr[lowerStart] - count += 1 - lowerStart += 1 - else: - tempArray[count] = arr[upperStart] - count += 1 - upperStart += 1 - - while lowerStart <= lowerStop: +def mergeSrt(arr, tempArray, lowerIndex, upperIndex): + if lowerIndex >= upperIndex: + return + middleIndex = (lowerIndex + upperIndex) / 2 + mergeSrt(arr, tempArray, lowerIndex, middleIndex) + mergeSrt(arr, tempArray, middleIndex + 1, upperIndex) + merge(arr, tempArray, lowerIndex, middleIndex, upperIndex) + +def merge(arr, tempArray, lowerIndex, middleIndex, upperIndex): + lowerStart = lowerIndex + lowerStop = middleIndex + upperStart = middleIndex + 1 + upperStop = upperIndex + count = lowerIndex + + while lowerStart <= lowerStop and upperStart <= upperStop: + if arr[lowerStart] < arr[upperStart]: tempArray[count] = arr[lowerStart] count += 1 lowerStart += 1 - - while upperStart <= upperStop: + else: tempArray[count] = arr[upperStart] count += 1 upperStart += 1 + + while lowerStart <= lowerStop: + tempArray[count] = arr[lowerStart] + count += 1 + lowerStart += 1 - i = lowerIndex - while i <= upperIndex: - arr[i] = tempArray[i] - i += 1 - + while upperStart <= upperStop: + tempArray[count] = arr[upperStart] + count += 1 + upperStart += 1 + + i = lowerIndex + while i <= upperIndex: + arr[i] = tempArray[i] + i += 1 -class MergeSortDemo(object): - @classmethod - def main(cls, args): - array = [3, 4, 2, 1, 6, 5, 7, 8, 1, 1] - MergeSort(array) - print array -if __name__ == '__main__': - import sys - MergeSortDemo.main(sys.argv) +array = [3, 4, 2, 1, 6, 5, 7, 8, 1, 1] +MergeSort(array) +print array diff --git a/Sorting/QuickSelect.py b/Sorting/QuickSelect.py index 7a6a1d2..d995cf1 100755 --- a/Sorting/QuickSelect.py +++ b/Sorting/QuickSelect.py @@ -1,47 +1,40 @@ #!/usr/bin/env python -class QuickSelect(object): - def Select(self, array, k): - self.arr = array - size = len(self.arr) - self.SelectUtil(self.arr, 0, size-1, k) - return self.arr[k-1] +def QuickSelect(array, k): + arr = array + size = len(arr) + SelectUtil(arr, 0, size-1, k) + return arr[k-1] - def SelectUtil(self, arr, lower, upper, k): - if upper <= lower: - return - pivot = arr[lower] - start = lower - stop = upper - while lower < upper: - while arr[lower] <= pivot and lower < upper: - lower += 1 - while arr[upper] > pivot and lower <= upper: - upper -= 1 - if lower < upper: - self.swap(arr, upper, lower) - self.swap(arr, upper, start) # upper is the pivot position - - if k < upper: - # pivot -1 is the upper for left sub array. - self.SelectUtil(arr, start, upper - 1, k) - - if k > upper: - # pivot + 1 is the lower for right sub array. - self.SelectUtil(arr, upper + 1, stop, k) - - def swap(self, arr, first, second): - temp = arr[first] - arr[first] = arr[second] - arr[second] = temp - - -class QuickSelectDemo(object): - @classmethod - def main(cls, args): - array = [3, 4, 2, 1, 6, 5, 7, 8, 10, 9] - value = QuickSelect().Select(array, 5) - print "value at index 5 is : " , value, +def SelectUtil(arr, lower, upper, k): + if upper <= lower: + return + pivot = arr[lower] + start = lower + stop = upper + while lower < upper: + while arr[lower] <= pivot and lower < upper: + lower += 1 + while arr[upper] > pivot and lower <= upper: + upper -= 1 + if lower < upper: + swap(arr, upper, lower) + swap(arr, upper, start) # upper is the pivot position + + if k < upper: + # pivot -1 is the upper for left sub array. + SelectUtil(arr, start, upper - 1, k) + + if k > upper: + # pivot + 1 is the lower for right sub array. + SelectUtil(arr, upper + 1, stop, k) + +def swap(arr, first, second): + temp = arr[first] + arr[first] = arr[second] + arr[second] = temp + + +array = [3, 4, 2, 1, 6, 5, 7, 8, 10, 9] +value = QuickSelect(array, 5) +print "value at index 5 is : " , value, -if __name__ == '__main__': - import sys - QuickSelectDemo.main(sys.argv) \ No newline at end of file diff --git a/Sorting/QuickSort.py b/Sorting/QuickSort.py index 2a9f248..ea13f75 100755 --- a/Sorting/QuickSort.py +++ b/Sorting/QuickSort.py @@ -1,43 +1,36 @@ #!/usr/bin/env python -class QuickSort(object): - def __init__(self, array): - self.arr = array - size = len(self.arr) - self.Sort(self.arr, 0, size - 1) +def QuickSort(array): + arr = array + size = len(arr) + QuickSortUtil(arr, 0, size - 1) - def Sort(self, arr, lower, upper): - if upper <= lower: - return - pivot = arr[lower] - start = lower - stop = upper - while lower < upper: - while arr[lower] <= pivot and lower < upper: - lower += 1 - while arr[upper] > pivot and lower <= upper: - upper -= 1 - if lower < upper: - self.swap(arr, upper, lower) - self.swap(arr, upper, start) - # upper is the pivot position - self.Sort(arr, start, upper - 1) - # pivot -1 is the upper for left sub array. - self.Sort(arr, upper + 1, stop) - # pivot + 1 is the lower for right sub array. - - def swap(self, arr, first, second): - temp = arr[first] - arr[first] = arr[second] - arr[second] = temp +def QuickSortUtil(arr, lower, upper): + if upper <= lower: + return + pivot = arr[lower] + start = lower + stop = upper + while lower < upper: + while arr[lower] <= pivot and lower < upper: + lower += 1 + while arr[upper] > pivot and lower <= upper: + upper -= 1 + if lower < upper: + swap(arr, upper, lower) + swap(arr, upper, start) + # upper is the pivot position + QuickSortUtil(arr, start, upper - 1) + # pivot -1 is the upper for left sub array. + QuickSortUtil(arr, upper + 1, stop) + # pivot + 1 is the lower for right sub array. + +def swap(arr, first, second): + temp = arr[first] + arr[first] = arr[second] + arr[second] = temp -class QuickSortDemo(object): - @classmethod - def main(cls, args): - array = [3, 4, 2, 1, 6, 5, 7, 8, 1, 1] - QuickSort(array) - print array -if __name__ == '__main__': - import sys - QuickSortDemo.main(sys.argv) +array = [3, 4, 2, 1, 6, 5, 7, 8, 1, 1] +QuickSort(array) +print array diff --git a/Sorting/SelectionSort.py b/Sorting/SelectionSort.py index 7f0d879..85d203e 100755 --- a/Sorting/SelectionSort.py +++ b/Sorting/SelectionSort.py @@ -1,49 +1,39 @@ #!/usr/bin/env python -class SelectionSort(object): - def __init__(self, array): - self.arr = array - self.sort() +def SelectionSort(arr): + # back array + size = len(arr) + i = 0 + while i < size - 1: + maxIndex = 0 + j = 1 + while j < size - 1 - i: + if arr[j] > arr[maxIndex]: + maxIndex = j + j += 1 + temp = arr[size - 1 - i] + arr[size - 1 - i] = arr[maxIndex] + arr[maxIndex] = temp + i += 1 - def sort(self): - # back array - size = len(self.arr) - i = 0 - while i < size - 1: - maxIndex = 0 - j = 1 - while j < size - 1 - i: - if self.arr[j] > self.arr[maxIndex]: - maxIndex = j - j += 1 - temp = self.arr[size - 1 - i] - self.arr[size - 1 - i] = self.arr[maxIndex] - self.arr[maxIndex] = temp - i += 1 +def SelectionSort2(arr): + # front array + size = len(arr) + i = 0 + while i < size - 1: + minIndex = i + j = i + 1 + while j < size: + if arr[j] < arr[minIndex]: + minIndex = j + j += 1 + temp = arr[i] + arr[i] = arr[minIndex] + arr[minIndex] = temp + i += 1 - def sort2(self): - # front array - size = len(self.arr) - i = 0 - while i < size - 1: - minIndex = i - j = i + 1 - while j < size: - if self.arr[j] < self.arr[minIndex]: - minIndex = j - j += 1 - temp = self.arr[i] - self.arr[i] = self.arr[minIndex] - self.arr[minIndex] = temp - i += 1 -class SelectionSortDemo(object): - @classmethod - def main(cls, args): - array = [9, 1, 8, 2, 7, 3, 6, 4, 5] - SelectionSort(array) - print array - -if __name__ == '__main__': - import sys - SelectionSortDemo.main(sys.argv) +array = [9, 1, 8, 2, 7, 3, 6, 4, 5] +SelectionSort(array) +print array + diff --git a/Stack/StackArr.py b/Stack/StackArr.py index f29de28..75bb770 100755 --- a/Stack/StackArr.py +++ b/Stack/StackArr.py @@ -25,16 +25,10 @@ def pop(self): def printStack(self): print self.data, -class StackDemo: - @classmethod - def main(cls, args): - s = Stack() - s.push(1) - s.push(2) - s.push(3) - s.pop() - s.printStack() - -if __name__ == '__main__': - import sys - StackDemo.main(sys.argv) \ No newline at end of file + +s = Stack() +s.push(1) +s.push(2) +s.push(3) +s.pop() +s.printStack() diff --git a/Stack/StackExercise.py b/Stack/StackExercise.py index b94728c..3de2477 100755 --- a/Stack/StackExercise.py +++ b/Stack/StackExercise.py @@ -1,259 +1,263 @@ #!/usr/bin/env python -class Algo: - @classmethod - def isBalancedParenthesis(cls, expn): - stk = [] - for ch in expn: - if ch == '{' or ch == '[' or ch == '(': - stk.append(ch) - elif ch == '}': - if stk.pop() != '{': - return False - elif ch == ']': - if stk.pop() != '[': - return False - elif ch == ')': - if stk.pop() != '(': - return False - return len(stk) == 0 - - - @classmethod - def main1(cls, args): - expn = "{()}[]" - value = Algo.isBalancedParenthesis(expn) - print "Given Expn:" , expn - print "Result after isParenthesisMatched:" , value - - @classmethod - def insertAtBottom(cls, stk, value): # !!!!!!!!! waste for python. - if len(stk) == 0: - stk.append(value) - else: - temp = stk.pop() - cls.insertAtBottom(stk, value) - stk.append(temp) - - @classmethod - def reverseStack(cls, stk): # !!!!!!!!! waste for python. - if len(stk) == 0: - return - else: - value = stk.pop - cls.reverseStack(stk) - cls.insertAtBottom(stk, value) - - @classmethod - def postfixEvaluate(cls, expn): - stk = [] - token_list = expn.split() - - for token in token_list: - if token == '+': - num1 = stk.pop(); - num2 = stk.pop(); - stk.append(num1 + num2) - elif token == '-': - num1 = stk.pop(); - num2 = stk.pop(); - stk.append(num1 - num2) - elif token == '*': - num1 = stk.pop(); - num2 = stk.pop(); - stk.append(num1 * num2) - elif token == '/': - num1 = stk.pop(); - num2 = stk.pop(); - stk.append(num1 / num2) - else: - stk.append(int(token)) - return stk.pop() - - @classmethod - def main2(cls, args): - expn = "6 5 2 3 + 8 * + 3 + *" - value = cls.postfixEvaluate(expn) - print "Given Postfix Expn: " , expn - print "Result after Evaluation: " , value - - @classmethod - def precedence(cls, x): - if x == '(': - return (0) - if x == '+' or x == '-': - return (1) - if x == '*' or x == '/' or x == '%': - return (2) - if x == '^': - return (3) - return (4) - - - @classmethod - def infixToPostfix(cls, expn): - stk = [] - token_list = expn.split() - output = "" - for token in token_list: - if token in '+-*/^': - while len(stk) != 0 and cls.precedence(token) <= cls.precedence(stk[len(stk) - 1]): - outsrt = stk.pop() +def isBalancedParenthesis(expn): + stk = [] + for ch in expn: + if ch == '{' or ch == '[' or ch == '(': + stk.append(ch) + elif ch == '}': + if stk.pop() != '{': + return False + elif ch == ']': + if stk.pop() != '[': + return False + elif ch == ')': + if stk.pop() != '(': + return False + return len(stk) == 0 + + + +def main1(): + expn = "{()}[]" + value = isBalancedParenthesis(expn) + print "Given Expn:" , expn + print "Result after isParenthesisMatched:" , value + + +def insertAtBottom(stk, value): # !!!!!!!!! waste for python. + if len(stk) == 0: + stk.append(value) + else: + temp = stk.pop() + insertAtBottom(stk, value) + stk.append(temp) + + +def reverseStack(stk): # !!!!!!!!! waste for python. + if len(stk) == 0: + return + else: + value = stk.pop + reverseStack(stk) + insertAtBottom(stk, value) + + +def postfixEvaluate(expn): + stk = [] + token_list = expn.split() + + for token in token_list: + if token == '+': + num1 = stk.pop(); + num2 = stk.pop(); + stk.append(num1 + num2) + elif token == '-': + num1 = stk.pop(); + num2 = stk.pop(); + stk.append(num1 - num2) + elif token == '*': + num1 = stk.pop(); + num2 = stk.pop(); + stk.append(num1 * num2) + elif token == '/': + num1 = stk.pop(); + num2 = stk.pop(); + stk.append(num1 / num2) + else: + stk.append(int(token)) + return stk.pop() + + +def main2(): + expn = "6 5 2 3 + 8 * + 3 + *" + value = postfixEvaluate(expn) + print "Given Postfix Expn: " , expn + print "Result after Evaluation: " , value + + +def precedence(x): + if x == '(': + return (0) + if x == '+' or x == '-': + return (1) + if x == '*' or x == '/' or x == '%': + return (2) + if x == '^': + return (3) + return (4) + + + +def infixToPostfix(expn): + stk = [] + token_list = expn.split() + output = "" + for token in token_list: + if token in '+-*/^': + while len(stk) != 0 and precedence(token) <= precedence(stk[len(stk) - 1]): + outsrt = stk.pop() + output = output + " " + outsrt + stk.append(token) + elif token == '(': + stk.append(token) + elif token == ')': + outsrt = None + while len(stk) != 0 and outsrt != '(': + outsrt = stk.pop() + if outsrt != '(' : output = output + " " + outsrt - stk.append(token) - elif token == '(': - stk.append(token) - elif token == ')': - outsrt = None - while len(stk) != 0 and outsrt != '(': - outsrt = stk.pop() - if outsrt != '(' : - output = output + " " + outsrt - else : - output = output + " " + token - - while len(stk) != 0: - outsrt = stk.pop() - output = output + " " + outsrt - return output - - @classmethod - def main5(cls, args): - expn = "10 + ( ( 3 ) ) * 5 / ( 16 - 4 )" - # value = cls.infixToPostfix(expn) - value = cls.infixToPrefix(expn) - print "Infix Expn: " , expn - print "Postfix Expn: " , value - - @classmethod - def infixToPrefix(cls, expn): - expn = cls.reverseString(expn) - expn = cls.replaceParanthesis(expn) - expn = cls.infixToPostfix(expn) - expn = cls.reverseString(expn) - return expn - - @classmethod - def replaceParanthesis(cls, expn): - lower = 0 - upper = len(expn) - newexp = "" - while lower < upper: - if expn[lower] == '(': - newexp += ')' - elif expn[lower] == ')': - newexp += '(' - else: - newexp += expn[lower] - lower += 1 - return newexp - - @classmethod - def reverseString(cls, expn): - lower = 0 - upper = len(expn) - newexp = "" - while lower < upper: - newexp += expn[upper - 1] - upper -= 1 - return newexp - - @classmethod - def main75(cls, args): - expn = "10+((3))*5/(16-4)" - value = cls.infixToPrefix(expn) - print "Infix Expn: " , expn - print "Prefix Expn: " , value - - @classmethod - def StockSpanRange(cls, arr): - SR = [0] * len(arr) - SR[0] = 1 - i = 1 - size = len(arr) + else : + output = output + " " + token - while i < size: - SR[i] = 1 - j = i - 1 - while (j >= 0) and (arr[i] >= arr[j]): - SR[i] += 1 - j -= 1 - i += 1 - return SR - - @classmethod - def main54(cls, args): - arr = [6, 5, 4, 3, 2, 4, 5, 7, 9] - value = cls.StockSpanRange2(arr) - print "StockSpanRange: " , value - - - + while len(stk) != 0: + outsrt = stk.pop() + output = output + " " + outsrt + return output + + +def main3(): + expn = "10 + ( ( 3 ) ) * 5 / ( 16 - 4 )" + # value = infixToPostfix(expn) + value = infixToPrefix(expn) + print "Infix Expn: " , expn + print "Postfix Expn: " , value + + +def infixToPrefix(expn): + expn = reverseString(expn) + expn = replaceParanthesis(expn) + expn = infixToPostfix(expn) + expn = reverseString(expn) + return expn + + +def replaceParanthesis(expn): + lower = 0 + upper = len(expn) + newexp = "" + while lower < upper: + if expn[lower] == '(': + newexp += ')' + elif expn[lower] == ')': + newexp += '(' + else: + newexp += expn[lower] + lower += 1 + return newexp + + +def reverseString(expn): + lower = 0 + upper = len(expn) + newexp = "" + while lower < upper: + newexp += expn[upper - 1] + upper -= 1 + return newexp + + +def main4(): + expn = "10+((3))*5/(16-4)" + value = infixToPrefix(expn) + print "Infix Expn: " , expn + print "Prefix Expn: " , value + + +def StockSpanRange(arr): + SR = [0] * len(arr) + SR[0] = 1 + i = 1 + size = len(arr) - @classmethod - def StockSpanRange2(self, arr): - stk = [] - size = len(arr) - SR = [0] * size - stk.append(0) - SR[0] = 1 - i = 1 - while i < size: - while len(stk) != 0 and arr[stk[len(stk) - 1]] <= arr[i]: - stk.pop() - if (len(stk) == 0): - SR[i] = i + 1 - else: - SR[i] = i - stk[len(stk) - 1] + while i < size: + SR[i] = 1 + j = i - 1 + while (j >= 0) and (arr[i] >= arr[j]): + SR[i] += 1 + j -= 1 + i += 1 + return SR + + +def main5(): + arr = [6, 5, 4, 3, 2, 4, 5, 7, 9] + value = StockSpanRange2(arr) + print "StockSpanRange: " , value + + + + + +def StockSpanRange2(arr): + stk = [] + size = len(arr) + SR = [0] * size + stk.append(0) + SR[0] = 1 + i = 1 + while i < size: + while len(stk) != 0 and arr[stk[len(stk) - 1]] <= arr[i]: + stk.pop() + if (len(stk) == 0): + SR[i] = i + 1 + else: + SR[i] = i - stk[len(stk) - 1] + stk.append(i) + i += 1 + return SR + + + + + +def GetMaxArea(arr): + size = len(arr) + maxArea = -1 + minHeight = 0 + i = 1 + while i < size: + minHeight = arr[i] + j = i - 1 + while j >= 0: + if minHeight > arr[j]: + minHeight = arr[j] + currArea = minHeight * (i - j + 1) + if maxArea < currArea: + maxArea = currArea + j -= 1 + i += 1 + return maxArea + + +def GetMaxArea2(arr): + """ generated source for method GetMaxArea2 """ + size = len(arr) + stk = [] + maxArea = 0 + i = 0 + while i < size: + while (i < size) and (len(stk) == 0 or arr[stk[len(stk) - 1]] <= arr[i]): stk.append(i) i += 1 - return SR - - @classmethod - def main(cls, args): - arr = [7, 6, 5, 4, 4, 1, 6, 3, 1] - value = cls.GetMaxArea2(arr) - print "GetMaxArea: " , value - - @classmethod - def GetMaxArea(cls, arr): - size = len(arr) - maxArea = -1 - minHeight = 0 - i = 1 - while i < size: - minHeight = arr[i] - j = i - 1 - while j >= 0: - if minHeight > arr[j]: - minHeight = arr[j] - currArea = minHeight * (i - j + 1) - if maxArea < currArea: - maxArea = currArea - j -= 1 - i += 1 - return maxArea - - @classmethod - def GetMaxArea2(cls, arr): - """ generated source for method GetMaxArea2 """ - size = len(arr) - stk = [] - maxArea = 0 - i = 0 - while i < size: - while (i < size) and (len(stk) == 0 or arr[stk[len(stk) - 1]] <= arr[i]): - stk.append(i) - i += 1 - while not len(stk) == 0 and (i == size or arr[stk[len(stk) - 1]] > arr[i]): - top = stk[len(stk) - 1] - stk.pop() - topArea = arr[top] * (i if len(stk) == 0 else i - stk[len(stk) - 1] - 1) - if maxArea < topArea: - maxArea = topArea - return maxArea - - -if __name__ == '__main__': - import sys - Algo.main(sys.argv) + while not len(stk) == 0 and (i == size or arr[stk[len(stk) - 1]] > arr[i]): + top = stk[len(stk) - 1] + stk.pop() + topArea = arr[top] * (i if len(stk) == 0 else i - stk[len(stk) - 1] - 1) + if maxArea < topArea: + maxArea = topArea + return maxArea + + +def main6(): + arr = [7, 6, 5, 4, 4, 1, 6, 3, 1] + value = GetMaxArea2(arr) + print "GetMaxArea: " , value + +main1() +main2() +main3() +main4() +main5() +main6() + diff --git a/Stack/StackList.py b/Stack/StackList.py index f64875f..3513178 100755 --- a/Stack/StackList.py +++ b/Stack/StackList.py @@ -39,16 +39,11 @@ def printStack(self): print temp.value, temp = temp.next -class StackDemo: - @classmethod - def main(cls, args): - s = Stack() - s.push(1) - s.push(2) - s.push(3) - s.pop() - s.printStack() - -if __name__ == '__main__': - import sys - StackDemo.main(sys.argv) \ No newline at end of file + +s = Stack() +s.push(1) +s.push(2) +s.push(3) +s.pop() +s.printStack() + diff --git a/Stack/TwoStack.py b/Stack/TwoStack.py index 1b9f0ed..a34733b 100755 --- a/Stack/TwoStack.py +++ b/Stack/TwoStack.py @@ -27,25 +27,19 @@ def StackPop2(self): self.size2 -= 1 return self.data.pop() -class TwoStackDemo: - @classmethod - def main(cls, args): - st = TwoStack() - i = 0 - while i < 10: - st.StackPush1(i) - i += 1 - j = 0 - while j < 10: - st.StackPush2(j + 10) - j += 1 - i = 0 - while i < 10: - # print "stack one pop value is : " , st.StackPop1() - print "stack two pop value is : " , st.StackPop2() - i += 1 +st = TwoStack() +i = 0 +while i < 10: + st.StackPush1(i) + i += 1 +j = 0 +while j < 10: + st.StackPush2(j + 10) + j += 1 +i = 0 +while i < 10: + # print "stack one pop value is : " , st.StackPop1() + print "stack two pop value is : " , st.StackPop2() + i += 1 -if __name__ == '__main__': - import sys - TwoStackDemo.main(sys.argv) diff --git a/String/StringTree.py b/String/StringTree.py index db6f89c..5bed9c2 100644 --- a/String/StringTree.py +++ b/String/StringTree.py @@ -83,31 +83,24 @@ def frequencyUtil(self, curr, value): return self.frequencyUtil(curr.rChild, value) -class StringTreeDemo: - @classmethod - def main(cls, args): - tt = StringTree() - tt.insert("banana") - tt.insert("apple") - tt.insert("mango") - tt.insert("banana") - tt.insert("apple") - tt.insert("mango") - tt.find("apple") - tt.find("banana") - tt.find("mango") - tt.find("banan") - tt.find("appletree") - tt.find("grapes") - - tt.printTree() - print "apple::" , tt.frequency("apple") - print "banana::" , tt.frequency("banana") - print "mango::" , tt.frequency("mango") - print "android::" , tt.frequency("android") +tt = StringTree() +tt.insert("banana") +tt.insert("apple") +tt.insert("mango") +tt.insert("banana") +tt.insert("apple") +tt.insert("mango") +tt.find("apple") +tt.find("banana") +tt.find("mango") +tt.find("banan") +tt.find("appletree") +tt.find("grapes") +tt.printTree() +print "apple::" , tt.frequency("apple") +print "banana::" , tt.frequency("banana") +print "mango::" , tt.frequency("mango") +print "android::" , tt.frequency("android") -if __name__ == '__main__': - import sys - StringTreeDemo.main(sys.argv) From b790587d16cef43f2457aeac753bd54aef098554 Mon Sep 17 00:00:00 2001 From: Hemant jain <32552737+Hemant-Jain-Author@users.noreply.github.com> Date: Thu, 6 Sep 2018 22:14:35 +0530 Subject: [PATCH 3/3] Update --- .gitignore | 1 + .vscode/launch.json | 116 ++++++++++++++++++++++++++++++++++++++++++++ BinaryTree/Tree.py | 57 ++++++++++------------ 3 files changed, 142 insertions(+), 32 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.gitignore b/.gitignore index e10e727..1ac3d63 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /.metadata/ +*.pyc diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..608b4f0 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,116 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Python: Current File", + "type": "python", + "request": "launch", + "program": "${file}" + }, + { + "name": "Python: Attach", + "type": "python", + "request": "attach", + "localRoot": "${workspaceFolder}", + "remoteRoot": "${workspaceFolder}", + "port": 3000, + "secret": "my_secret", + "host": "localhost" + }, + { + "name": "Python: Terminal (integrated)", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "integratedTerminal" + }, + { + "name": "Python: Terminal (external)", + "type": "python", + "request": "launch", + "program": "${file}", + "console": "externalTerminal" + }, + { + "name": "Python: Django", + "type": "python", + "request": "launch", + "program": "${workspaceFolder}/manage.py", + "args": [ + "runserver", + "--noreload", + "--nothreading" + ], + "debugOptions": [ + "RedirectOutput", + "Django" + ] + }, + { + "name": "Python: Flask (0.11.x or later)", + "type": "python", + "request": "launch", + "module": "flask", + "env": { + "FLASK_APP": "${workspaceFolder}/app.py" + }, + "args": [ + "run", + "--no-debugger", + "--no-reload" + ] + }, + { + "name": "Python: Module", + "type": "python", + "request": "launch", + "module": "module.name" + }, + { + "name": "Python: Pyramid", + "type": "python", + "request": "launch", + "args": [ + "${workspaceFolder}/development.ini" + ], + "debugOptions": [ + "RedirectOutput", + "Pyramid" + ] + }, + { + "name": "Python: Watson", + "type": "python", + "request": "launch", + "program": "${workspaceFolder}/console.py", + "args": [ + "dev", + "runserver", + "--noreload=True" + ] + }, + { + "name": "Python: All debug Options", + "type": "python", + "request": "launch", + "pythonPath": "${config:python.pythonPath}", + "program": "${file}", + "module": "module.name", + "env": { + "VAR1": "1", + "VAR2": "2" + }, + "envFile": "${workspaceFolder}/.env", + "args": [ + "arg1", + "arg2" + ], + "debugOptions": [ + "RedirectOutput" + ] + } + ] +} \ No newline at end of file diff --git a/BinaryTree/Tree.py b/BinaryTree/Tree.py index 71005a6..a7562ca 100644 --- a/BinaryTree/Tree.py +++ b/BinaryTree/Tree.py @@ -1,13 +1,14 @@ #!/usr/bin/env python from collections import deque + class Tree(object): class Node(object): def __init__(self, v, l=None, r=None): self.value = v self.lChild = l - self.rChild = r - + self.rChild = r + def __init__(self): self.root = None @@ -24,7 +25,7 @@ def levelOrderBinaryTreeUtil(self, arr, start): if right < size: curr.rChild = self.levelOrderBinaryTreeUtil(arr, right) return curr - + def InsertNode(self, value): self.root = self.InsertNodeUtil(self.root, value) @@ -38,25 +39,22 @@ def InsertNodeUtil(self, node, value): node.rChild = self.InsertNodeUtil(node.rChild, value) return node - def PrintPreOrder(self): self.PrintPreOrderUtil(self.root) - def PrintPreOrderUtil(self, node): - # pre order + # pre order if node != None: print (node.value), self.PrintPreOrderUtil(node.lChild) self.PrintPreOrderUtil(node.rChild) - def NthPreOrder(self, index): - count = [0] + count = [0] self.NthPreOrderUtil(self.root, index, count) def NthPreOrderUtil(self, node, index, count): - # pre order + # pre order if node != None: count[0] += 1 if count[0] == index: @@ -64,24 +62,22 @@ def NthPreOrderUtil(self, node, index, count): self.NthPreOrderUtil(node.lChild, index, count) self.NthPreOrderUtil(node.rChild, index, count) - def PrintPostOrder(self): self.PrintPostOrderUtil(self.root) def PrintPostOrderUtil(self, node): - # post order + # post order if node != None: self.PrintPostOrderUtil(node.lChild) self.PrintPostOrderUtil(node.rChild) print (node.value), - def NthPostOrder(self, index): count = [0] self.NthPostOrderUtil(self.root, index, count) def NthPostOrderUtil(self, node, index, count): - # post order + # post order if node != None: self.NthPostOrderUtil(node.lChild, index, count) self.NthPostOrderUtil(node.rChild, index, count) @@ -89,24 +85,20 @@ def NthPostOrderUtil(self, node, index, count): if count[0] == index: print (node.value), - def PrintInOrder(self): self.PrintInOrderUtil(self.root) - def PrintInOrderUtil(self, node): - # In order + # In order if node != None: self.PrintInOrderUtil(node.lChild) print (node.value), self.PrintInOrderUtil(node.rChild) - def NthInOrder(self, index): count = [0] self.NthInOrderUtil(self.root, index, count) - def NthInOrderUtil(self, node, index, count): if node != None: self.NthInOrderUtil(node.lChild, index, count) @@ -135,10 +127,11 @@ def PrintDepthFirst(self): while stk.isEmpty() == False: temp = stk.pop() print (temp.value), - if temp.lChild != None: - stk.append(temp.lChild) if temp.rChild != None: stk.append(temp.rChild) + if temp.lChild != None: + stk.append(temp.lChild) + def Find(self, value): curr = self.root @@ -638,12 +631,12 @@ def treeToListRec(self, curr): return Head -#======================================================================= +# ======================================================================= # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # t2 = Tree() # t2.levelOrderBinaryTree(arr) -#======================================================================= -#======================================================================= +# ======================================================================= +# ======================================================================= # t = Tree() # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # # t.levelOrderBinaryTree(arr) @@ -674,11 +667,11 @@ def treeToListRec(self, curr): # t.PrintBredthFirst() # # t.treeToList(); # print ( t.LCA(10, 3) ) -#======================================================================= +# ======================================================================= arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] t2 = Tree() # t2.levelOrderBinaryTree(arr) -#======================================================================= +# ======================================================================= # t2.InsertNode(5) # t2.InsertNode(3) # t2.InsertNode(4) @@ -687,10 +680,10 @@ def treeToListRec(self, curr): # t2.InsertNode(8) # t2.InsertNode(7) # t2.InsertNode(9) -#======================================================================= -#print t2.Ancestor(1, 10) -#print t2.CeilBST(7) -#print t2.FloorBST(12) +# ======================================================================= +# print t2.Ancestor(1, 10) +# print t2.CeilBST(7) +# print t2.FloorBST(12) t2.CreateBinaryTree(arr) t2.PrintInOrder() print "" @@ -703,8 +696,8 @@ def treeToListRec(self, curr): t2.PrintPreOrder() print "" t2.iterativePreOrder() -#t2.DeleteNode(8) -#======================================================================= +# t2.DeleteNode(8) +# ======================================================================= # t3 = t2.CopyMirrorTree() # t2.PrintInOrder() # print "" @@ -737,5 +730,5 @@ def treeToListRec(self, curr): # print t2.printInRange(4, 7) # print t2.trimOutsideRange(3, 8) # print t2.PrintInOrder() -#======================================================================= +# =======================================================================