├── Table of Contents [Data Structure and Algorithmic Thinking with Python].pdf ├── Sample Linked Lists Chapter [Data Structure and Algorithmic Thinking with Python].pdf ├── Errata ├── src ├── chapter04stacks │ ├── largestHistrogram_n^2.py │ ├── largestHistrogram_n^3.py │ ├── FindingSpansNotEfficient.py │ ├── IsPalindrome2.py │ ├── QueueWithStacks.py │ └── RemoveAdjacentDuplicates.py ├── chapter11searching │ ├── finding_all_peaks_with_linear_search.py │ ├── finding_highest_peak_with_linear_search.py │ ├── finding_single_peak_with_linear_search.py │ ├── finding_peak_with_binary_search.py │ ├── FoundNumberOfOccurences.py │ ├── SingleNumber.py │ ├── RemoveDuplicatesWithHash.py │ ├── singleUniqueNumber.py │ ├── FindMissingNumberEfficientWithXOR.py │ ├── ShuffleArray.py │ ├── CheckPairwiseSortedness.py │ ├── LinearSearch.py │ ├── PrintTwoRepeatedElementsBruteForce.py │ ├── RemoveDuplicatesWithSort.py │ ├── RemoveAdjacentRepeats.py │ ├── FindMissingNumberBruteForce.py │ ├── FindNonrepeatedCharacterBruteForce.py │ ├── TwoElementsWithSumKBruteForce.py │ ├── planting.py │ ├── RearrangeArrayElementsA1B1A2B2.py │ ├── CheckDuplicatesSorting.py │ ├── MaxRepititionsEfficient.py │ ├── CheckDuplicatesNegationTechnique.py │ ├── FirstRepeatedCharacterWithHash.py │ ├── FrequencyCounter.py │ ├── MajorityElement.py │ ├── pivot.py │ ├── CheckDuplicatesBruteForce.py │ ├── FirstRepeatedChar.py │ ├── MaxIndexDifferenceBruteForce.py │ ├── SeparateZerosAndOnes.py │ ├── SeparateODDAndEvenNumbers.py │ ├── PrintTwoRepeatedElementsHash.py │ ├── RemoveDuplicatesBruteForce.py │ ├── ThreeElementsWithSumKBruteForce.py │ ├── MaxRepititionsBruteForce.py │ ├── MoveSpacesToEnd.py │ ├── RemoveCharsFromString.py │ ├── TwoElementsWithSumKEfficientWithSorting.py │ ├── BinarySearchIterative.py │ ├── FindMissingNumberFromGivenRange.py │ ├── FindNonrepeatedCharacterWithHash.py │ ├── PrintTwoRepeatedElementsHash2.py │ ├── TwoElementsWithSumKWithHash.py │ ├── MatrixSortedFind.py │ ├── MaxRepititionsWithSort.py │ ├── ReplaceWithNearestGreaterElement.py │ ├── CheckWhoWinsTheElection.py │ ├── FrequencyCounterWithoutExtraSpace.py │ ├── MaxRepititionsWithHash.py │ ├── CheckWhoWinsTheElectionWithOutSpace.py │ ├── FindInRotatedSortedArray.py │ ├── TwoElementsClosestToZeroBruteForce.py │ ├── ThreeElementsWithSumKWithSorting.py │ ├── MaxIndexDifferenceEfficient.py │ ├── BinarySearcLastOccurrence.py │ ├── BinarySearchFirstOccurrence.py │ ├── MoveZerosToEnd.py │ ├── BinarySearchRecursive.py │ ├── FinSUMInTwoSortedArrays.py │ ├── FindMinimumInRotatedSortedArray.py │ ├── FindTwoRepeatingNumbersWithXOR.py │ ├── TwoElementsClosestToZeroWithSorting.py │ ├── FirstRepeatedElementAmongRepeatedElementsWithHash.py │ └── InterpolationSearch.py ├── chapter18divideandconquer │ ├── finding_all_peaks_with_linear_search.py │ ├── finding_single_peak_with_linear_search.py │ ├── finding_peak_with_binary_search.py │ ├── finding_highest_peak_with_linear_search.py │ ├── BinarySearchIterative.py │ ├── ClosestPairBruteForce.py │ ├── ShuffleArrayWithDivideAndConquer.py │ ├── ExponentialWithDivideAndConquer.py │ ├── BinarySearchRecursive.py │ └── find_peak-2d.py ├── chapter12selectionalgorithms │ ├── FindMinMaxWithPairComparisons.py │ ├── FindLargestInArray.py │ └── FindSmallestAndLargestInArray.py ├── chapter19dynamicprogramming │ ├── FiboWithoutDP.py │ ├── RecursiveFibo.py │ ├── tribonacci_series.py │ ├── FiboWithDPBottomUp.py │ ├── FactorialRecursive.py │ ├── CatalanRecursive.py │ ├── FiboWithDPTopDown.py │ ├── CatalanWithDP.py │ ├── CatalanWithFormula.py │ ├── longest_common_subsequence_recursive.py │ ├── FactorialwithDP.py │ ├── LongestCommonSubsequenceWithoutDP.py │ ├── PetrolStationsDPProblem.py │ ├── SubsetSum.py │ ├── SubsetSum2.py │ ├── SubsetSumWithDP.py │ ├── LongestIncreasingSubSeq.py │ ├── LongestIncreasingSequence2.py │ ├── MaxContigousSumWithNSquare.py │ ├── EditDistance.py │ ├── MaxContigousSumBruteForce.py │ ├── MaxContigousSumWithoutDPEfficient.py │ ├── 01KnapSackWithDP.py │ ├── MaxContigousSumWithDP.py │ ├── MinJumpsDP.py │ ├── MaxSumWithNoTwoContinuousNumbers.py │ ├── LargestRectangleArea.py │ ├── MakingChangeWithDP.py │ ├── LongestPalindromeSubsequence.py │ ├── StrategyOfCoinsGameWithDP.py │ ├── Count_Apples_with_3ways_of_reaching.py │ └── RecusriveFunctionDPFromReccurence.py ├── chapter01introduction │ ├── NestedLoop.py │ ├── SimpleLoop.py │ ├── NPower5Complexity.py │ ├── LogLogNComplexity.py │ ├── RecursiveComplexity.py │ ├── Logarithms.py │ ├── LogSquareNComplexity.py │ ├── SqrtComplextity.py │ ├── ComplexityWithBreakStatement.py │ ├── NCubeLognComplexity.py │ ├── NLogSquareComplexity.py │ ├── NSquareLogNComplexity.py │ ├── RecursiveNComplexity.py │ ├── NLogNwithLoops.py │ └── RecursiveComplexityFNby3.py ├── chapter03linkedlists │ ├── RotateList.py │ ├── MergeSecondListToFirst.py │ ├── DeleteLinkedListDuplicates.py │ ├── ReverseInPairs.py │ ├── FindIntersectingNodeUsingHash.py │ ├── NumberOfConnectedComponents.py │ ├── DLLToBST.py │ ├── MergeTwoLists.py │ ├── MergeTwoSortedLists.py │ ├── ReorderList.py │ ├── OrderedInsertLinkedList.py │ ├── NthNodeFromEnd.py │ └── GetIntersectionNode.py ├── chapter21miscconcepts │ ├── NumberOfOccurences.py │ ├── ReverseinBinary.py │ ├── ShuffleArray.py │ ├── NumberOfTrailingZerosOfFactorialNumber.py │ ├── ShuffleCards.py │ ├── MatrixSortedFind.py │ ├── CountNumberofSetbitsin1toN.py │ ├── NumberPlusone.py │ ├── SprialIterativePrint.py │ └── NumberOfOneBits.py ├── chapter14hashing │ ├── RemoveDuplicatesWithHash.py │ ├── FirstRepeatedCharacterWithHash.py │ └── FindNonrepeatedCharacterWithHash.py ├── chapter10sorting │ ├── MergeSecondListToFirst.py │ ├── InsertionSort.py │ ├── SortListByFrequency.py │ ├── BubbleSort.py │ ├── SeletionSort.py │ ├── BubbleSortImproved.py │ ├── Create SortedSquaredArray.py │ ├── CheckWhoWinsTheElection.py │ ├── CheckWhoWinsTheElectionWithOutSpace.py │ ├── QuickSort2.py │ ├── RadixSort.py │ ├── FinSUMInTwoSortedArrays.py │ └── QuickSort.py ├── chapter06trees │ ├── PrintAllAncestors.py │ ├── MirrorOfBinaryTree.py │ ├── AreMirrors.py │ ├── AugmentedTreesKthSmallest.py │ ├── SortedArrayToBST.py │ ├── BSTFind.py │ ├── FillNextSiblings.py │ ├── TrimBST.py │ ├── TreeCompressionBST.py │ ├── DLLToBST.py │ ├── SuccessorPredessor.py │ ├── DepthOfGenericTreeFromArray.py │ ├── RootToLeavesTotalSum.py │ ├── LCAInBinaryTree.py │ ├── PrintPathsRecur.py │ ├── CountBSTs.py │ ├── TreemaxDepth.py │ ├── AreStructurullySameTrees.py │ └── CheckPathWithSum.py ├── chapter17greedyalgorithms │ └── LargestTasks.py ├── chapter15stringalgorithms │ ├── FindNonrepeatedCharacterBruteForce.py │ ├── FirstRepeatedCharacterWithHash.py │ ├── RemoveCharsFromString.py │ ├── FindNonrepeatedCharacterWithHash.py │ ├── StrstrBruteForce.py │ ├── PrintInterleavings.py │ ├── RemoveAdjacentDuplicates.py │ ├── ReverseWordsInSentence.py │ └── Combinations.py ├── chapter02recursionandbacktracking │ ├── KBitSequences.py │ └── BitSequences.py ├── chapter05queues │ ├── MinSlidingWindowWithDequeue.py │ ├── Dequeue.py │ └── QueueWithStacks.py ├── chapter07priorityqueues │ ├── MaxSlidingWindowWithHeap.py │ └── MinSlidingWindowWithDequeue.py └── chapter09graphs │ ├── DetectCycleInGraph.py │ ├── CutVertices.py │ └── BridgesInGraphs.py ├── .pydevproject ├── .project └── README.md /Table of Contents [Data Structure and Algorithmic Thinking with Python].pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careermonk/data-structures-and-algorithmic-thinking-with-python/HEAD/Table of Contents [Data Structure and Algorithmic Thinking with Python].pdf -------------------------------------------------------------------------------- /Sample Linked Lists Chapter [Data Structure and Algorithmic Thinking with Python].pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/careermonk/data-structures-and-algorithmic-thinking-with-python/HEAD/Sample Linked Lists Chapter [Data Structure and Algorithmic Thinking with Python].pdf -------------------------------------------------------------------------------- /Errata: -------------------------------------------------------------------------------- 1 | List of Code Issues Fixed: 2 | 3 | https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/commit/b61548efd21bc6fc2d96645b4acce3084670de53 4 | https://github.com/careermonk/DataStructureAndAlgorithmicThinkingWithPython/commit/a8d3729ace3289c2291b009f3273fa77ad8800ea 5 | -------------------------------------------------------------------------------- /src/chapter04stacks/largestHistrogram_n^2.py: -------------------------------------------------------------------------------- 1 | 2 | def largestHistrogram(A): 3 | maxArea = 0 4 | for i in range(len(A)): 5 | minimum_height = A[i] 6 | for j in range(i, len(A)): 7 | minimum_height = min(minimum_height, A[j]) 8 | maxArea = max(maxArea, (j-i+1) * minimum_height) 9 | return maxArea 10 | 11 | 12 | A = [6, 2, 5, 4, 5, 1, 6] 13 | print "largestRectangleArea: ", largestHistrogram(A) 14 | -------------------------------------------------------------------------------- /src/chapter11searching/finding_all_peaks_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peaks(A): 2 | peak = A[0] 3 | for i in range(1, len(A)-2): 4 | prev = A[i-1] 5 | curr = A[i] 6 | next = A[i+1] 7 | if curr > prev and curr > next: 8 | index = i 9 | peak = curr 10 | print peak 11 | if A[len(A)-1] > A[len(A)-2]: 12 | print A[len(A)-1] 13 | 14 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 15 | print A, "\n" 16 | find_peaks(A) 17 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/finding_all_peaks_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peaks(A): 2 | peak = A[0] 3 | for i in range(1, len(A)-2): 4 | prev = A[i-1] 5 | curr = A[i] 6 | next = A[i+1] 7 | if curr > prev and curr > next: 8 | index = i 9 | peak = curr 10 | print peak 11 | if A[len(A)-1] > A[len(A)-2]: 12 | print A[len(A)-1] 13 | 14 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 15 | print A, "\n" 16 | find_peaks(A) 17 | -------------------------------------------------------------------------------- /.pydevproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /${PROJECT_DIR_NAME}/src 5 | 6 | python 2.7 7 | Default 8 | 9 | -------------------------------------------------------------------------------- /src/chapter11searching/finding_highest_peak_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | peak = A[0] 3 | for i in range(1, len(A)-2): 4 | prev = A[i-1] 5 | curr = A[i] 6 | next = A[i+1] 7 | if curr > prev and curr > next: 8 | index = i 9 | peak = curr 10 | 11 | if len(A)-1 > peak: 12 | return A[len(A)-1] 13 | 14 | return A[index] 15 | 16 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 17 | print A, "\n", find_peak(A) 18 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | DataStructureAndAlgorithmicThinkingWithPython 4 | 5 | 6 | 7 | 8 | 9 | org.python.pydev.PyDevBuilder 10 | 11 | 12 | 13 | 14 | 15 | org.python.pydev.pythonNature 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/chapter11searching/finding_single_peak_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | peak = A[0] 3 | for i in range(1, len(A)-2): 4 | prev = A[i-1] 5 | curr = A[i] 6 | next = A[i+1] 7 | if curr > prev and curr > next: 8 | index = i 9 | peak = curr 10 | return peak 11 | 12 | if len(A)-1 > peak: 13 | return A[len(A)-1] 14 | 15 | return A[index] 16 | 17 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 18 | print A, "\n", find_peak(A) 19 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/finding_single_peak_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | peak = A[0] 3 | for i in range(1, len(A)-2): 4 | prev = A[i-1] 5 | curr = A[i] 6 | next = A[i+1] 7 | if curr > prev and curr > next: 8 | index = i 9 | peak = curr 10 | return peak 11 | 12 | if len(A)-1 > peak: 13 | return A[len(A)-1] 14 | 15 | return A[index] 16 | 17 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 18 | print A, "\n", find_peak(A) 19 | -------------------------------------------------------------------------------- /src/chapter11searching/finding_peak_with_binary_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | if not A: 3 | return -1 4 | 5 | l, r = 0, len(A) - 1 6 | while l + 1 < r: 7 | mid = l + (r - l) / 2 8 | if A[mid] < A[mid - 1]: 9 | r = mid 10 | elif A[mid] < A[mid + 1]: 11 | l = mid 12 | else: 13 | return mid 14 | mid = l if A[l] > A[r] else r 15 | return mid 16 | 17 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 18 | p = find_peak(A) 19 | print A, "\n", A[p] 20 | -------------------------------------------------------------------------------- /src/chapter04stacks/largestHistrogram_n^3.py: -------------------------------------------------------------------------------- 1 | def findMin(A, i, j): 2 | min = A[i] 3 | while i <= j: 4 | if min > A[i]: 5 | min = A[i] 6 | i = i + 1 7 | return min 8 | 9 | def largestHistrogram(A): 10 | maxArea = 0 11 | print A 12 | for i in range(len(A)): 13 | for j in range(i, len(A)): 14 | minimum_height = A[i] 15 | minimum_height = findMin(A, i, j) 16 | maxArea = max(maxArea, (j-i+1) * minimum_height) 17 | return maxArea 18 | 19 | 20 | A = [6, 2, 5, 4, 5, 1, 6] 21 | print "largestRectangleArea: ", largestHistrogram(A) 22 | -------------------------------------------------------------------------------- /src/chapter11searching/FoundNumberOfOccurences.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | -------------------------------------------------------------------------------- /src/chapter12selectionalgorithms/FindMinMaxWithPairComparisons.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/finding_peak_with_binary_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | if not A: 3 | return -1 4 | 5 | left, right = 0, len(A) - 1 6 | while left + 1 < right: 7 | mid = left + (right - left) / 2 8 | if A[mid] < A[mid - 1]: 9 | right = mid 10 | elif A[mid] < A[mid + 1]: 11 | left = mid 12 | else: 13 | return mid 14 | mid = left if A[left] > A[right] else right 15 | return mid 16 | 17 | A = [35, 5, 20, 2, 40, 25, 80, 25, 15, 40] 18 | peak = find_peak(A) 19 | print A, "\n", A[peak] 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DataStructure And Algorithmic Thinking With Python 2 | -------------------------------------------------- 3 | 4 | Copyright (c) Oct 22, 2018 CareerMonk Publications and others. 5 | 6 | E-Mail : info@careermonk.com 7 | 8 | Last modification by : Narasimha Karumanchi 9 | 10 | Book Title : DataStructure And Algorithmic Thinking With Python 11 | 12 | ISBN : 9788192107592 13 | 14 | Warranty : This software is provided "as is" without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. 15 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/finding_highest_peak_with_linear_search.py: -------------------------------------------------------------------------------- 1 | def find_peak(A): 2 | max_peak_value = max_peak_index = -1 3 | peak = A[0] 4 | index = 0 5 | for i in range(1, len(A)-1): 6 | prev = A[i-1] 7 | curr = A[i] 8 | next = A[i+1] 9 | if curr > prev and curr > next: 10 | index = i 11 | peak = curr 12 | if peak > max_peak_value: 13 | max_peak_value, max_peak_index = peak, index 14 | 15 | if A[len(A)-1] > peak: 16 | return A[len(A)-1], len(A)-1 17 | 18 | return max_peak_value, max_peak_index 19 | 20 | A = [35, 5, 20, 2, 90, 25, 80, 25, 115, 40] 21 | print A, "\n", find_peak(A) 22 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/FiboWithoutDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Fibo(n): 12 | a, b = 0, 1 13 | for i in range(n): 14 | a, b = b, a + b 15 | return a 16 | 17 | print(Fibo(10)) 18 | -------------------------------------------------------------------------------- /src/chapter01introduction/NestedLoop.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | #!/usr/bin/python 13 | 14 | n = 10 15 | for i in range(1, n): 16 | for j in range(1, n): 17 | print 'i value %d and j value %d' % (i, j) 18 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/RotateList.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def rotateList(A, K): 12 | n = K % len(A) 13 | word = A[::-1] 14 | return A[n:] + word[len(A) - n:] 15 | A = [7, 3, 2, 3, 3, 6, 3] 16 | print A, rotateList(A, 3) 17 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/RecursiveFibo.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Fibo(n): 12 | if n == 0: return 0 13 | elif n == 1: return 1 14 | else: return Fibo(n - 1) + Fibo(n - 2) 15 | 16 | Fibo(10) 17 | -------------------------------------------------------------------------------- /src/chapter11searching/SingleNumber.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def singleNumber(A): 12 | i = res = 0 13 | for i in range (0, len(A)): 14 | res = res ^ A[i] 15 | return res 16 | 17 | A = [7, 3, 6, 3, 3, 6, 7 ] 18 | print singleNumber(A) 19 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/tribonacci_series.py: -------------------------------------------------------------------------------- 1 | def trib_recursive(n): 2 | if n == 0: return 0 3 | elif n == 1: return 1 4 | elif n == 2: return 2 5 | else: return trib_recursive(n-1)+ trib_recursive(n-2) + trib_recursive(n-3) 6 | 7 | print (trib_recursive(10)) 8 | 9 | 10 | def trib_dep(n): 11 | tribTable = [0 for x in range(n+1)] 12 | tribTable[0] = 0 13 | tribTable[1] = 1 14 | tribTable[2] = 2 15 | for i in range(3, n+1): 16 | tribTable[i] = tribTable[i-1] + tribTable[i-2] + tribTable[i-3] 17 | return tribTable[n] 18 | 19 | print(trib_dep(10)) 20 | 21 | def trib_iterative(n): 22 | a, b, c = 0, 1, 2 23 | for i in range(n): 24 | a, b, c = b, c, a + b + c 25 | return a 26 | 27 | print(trib_iterative(10)) 28 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/FiboWithDPBottomUp.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Fibo(n): 12 | fibTable = [0, 1] 13 | for i in range(2, n + 1): 14 | fibTable.append(fibTable[i - 1] + fibTable[i - 2]) 15 | return fibTable[n] 16 | 17 | print(Fibo(10)) 18 | -------------------------------------------------------------------------------- /src/chapter01introduction/SimpleLoop.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | n = 10 13 | # outer loop executed n times 14 | for i in range(1, n): 15 | # inner loop executes n times 16 | for j in range(1, n): 17 | print 'i value %d and j value %d' % (i, j) # constant time 18 | -------------------------------------------------------------------------------- /src/chapter01introduction/NPower5Complexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | for i in range(1, n): 14 | j = i 15 | while j < i * i: 16 | j = j + 1 17 | if j % i == 0: 18 | for k in range(0, j): 19 | print(" * ") 20 | 21 | function(10) 22 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/NumberOfOccurences.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def linear_search_count(A, data): 12 | count = 0 13 | for i in range (0, len(A)): 14 | if(A[i] == data): 15 | count += 1 16 | return count 17 | 18 | A = [7, 3, 6, 3, 3, 6, 7 ] 19 | print linear_search_count(A, 7) 20 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/FactorialRecursive.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def factorial(n): 12 | if n == 0: return 1 13 | return n * factorial(n - 1) 14 | 15 | print(factorial(10))def factorial(n): 16 | if n == 0: return 1 17 | return n * factorial(n - 1) 18 | 19 | print(factorial(10)) 20 | -------------------------------------------------------------------------------- /src/chapter01introduction/LogLogNComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | import math 13 | count = 0 14 | def function(n): 15 | global count 16 | if n <= 2: 17 | return 1 18 | else: 19 | function(round(math.sqrt(n))) 20 | count = count + 1 21 | return count 22 | 23 | print(function(200)) 24 | -------------------------------------------------------------------------------- /src/chapter01introduction/RecursiveComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | count = 0 14 | if n <= 0: 15 | return 16 | for i in range(1, n): 17 | for j in range(1, n): 18 | count = count + 1 19 | function(n - 3) 20 | print (count) 21 | 22 | function(20) 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/chapter01introduction/Logarithms.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def logarithms(n): 13 | i = n 14 | while i >= 1: 15 | i = i // 2 16 | print i 17 | 18 | logarithms(100) 19 | 20 | 21 | def logarithms2(n): 22 | i = 1 23 | while i <= n: 24 | i = i * 2 25 | print i 26 | 27 | logarithms(100) 28 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/MergeSecondListToFirst.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Merge(A, m, B, n): 12 | i = n - 1 13 | j = k = m - 1 14 | while k >= 0: 15 | if(B[i] > A[j] or j < 0): 16 | A[k] = B[i] 17 | i -= 1 18 | if(i < 0): 19 | break 20 | else: 21 | A[k] = A[j] 22 | j -= 1 23 | k -= 1 24 | -------------------------------------------------------------------------------- /src/chapter14hashing/RemoveDuplicatesWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | A = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] 12 | unique = [] 13 | helperSet = set() 14 | for x in A: 15 | if x not in helperSet: 16 | unique.append(x) 17 | helperSet.add(x) 18 | 19 | print A 20 | print unique 21 | -------------------------------------------------------------------------------- /src/chapter01introduction/LogSquareNComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | count = 0 13 | def logarithms(n): 14 | i = 1 15 | global count 16 | while i <= n: 17 | j = n 18 | while j > 0: 19 | j = j // 2 20 | count = count + 1 21 | i = i * 2 22 | return count 23 | 24 | print(logarithms(10)) 25 | -------------------------------------------------------------------------------- /src/chapter10sorting/MergeSecondListToFirst.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Merge(A, m, B, n): 12 | i = n - 1 13 | j = k = m - 1 14 | while k >= 0: 15 | if(B[i] > A[j] or j < 0): 16 | A[k] = B[i] 17 | i -= 1 18 | if(i < 0): 19 | break 20 | else: 21 | A[k] = A[j] 22 | j -= 1 23 | k -= 1 24 | -------------------------------------------------------------------------------- /src/chapter11searching/RemoveDuplicatesWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | A = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] 12 | unique = [] 13 | helperSet = set() 14 | for x in A: 15 | if x not in helperSet: 16 | unique.append(x) 17 | helperSet.add(x) 18 | 19 | print A 20 | print unique 21 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/CatalanRecursive.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CatalanRecursive(n): 12 | if n == 0: 13 | return 1 14 | else: 15 | count = 0 16 | for i in range(n): 17 | count += CatalanRecursive(i) * CatalanRecursive(n - 1 - i) 18 | return count 19 | 20 | print CatalanRecursive(4) 21 | -------------------------------------------------------------------------------- /src/chapter06trees/PrintAllAncestors.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def PrintAllAncestors(root, node): 12 | if(root == NULL): 13 | return 0 14 | if(root.left == node or root.right == node or PrintAllAncestors(root.left, node) or PrintAllAncestors(root.right, node)): 15 | print(root.data) 16 | return 1 17 | return 0 18 | -------------------------------------------------------------------------------- /src/chapter12selectionalgorithms/FindLargestInArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FindLargestInArray(A): 12 | max = 0 13 | for number in A: 14 | if number > max: 15 | max = number 16 | return max 17 | 18 | print(FindLargestInArray([2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13])) 19 | -------------------------------------------------------------------------------- /src/chapter11searching/singleUniqueNumber.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | class Solution(object): 12 | def singleNumber(self, A): 13 | """ 14 | :type A: List[int] 15 | :rtype: int 16 | """ 17 | result = 0 18 | for n in A: 19 | result ^= n 20 | return result 21 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/ReverseinBinary.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def reverse_number(n): 12 | nReverse = n 13 | s = n.bit_length() 14 | while(n): 15 | nReverse <<= 1 16 | nReverse |= (n & 1) 17 | s -= 1 18 | n >>= 1 19 | nReverse <<= s 20 | print nReverse 21 | 22 | n = 4 23 | print n 24 | reverse_number(n) 25 | -------------------------------------------------------------------------------- /src/chapter11searching/FindMissingNumberEfficientWithXOR.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FindMissingNumber(A): 12 | n = len(A) 13 | X = 0 14 | for i in range(1, n + 2): 15 | X = X ^ i 16 | for i in range(0, n): 17 | X = X ^ A[i] 18 | print "Missing number is ", X 19 | A = [8, 2, 1, 4, 6, 5, 7, 9] 20 | FindMissingNumber(A) 21 | -------------------------------------------------------------------------------- /src/chapter17greedyalgorithms/LargestTasks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def LargestTasks(Start, n, Finish): 12 | sort Finish[] 13 | rearrange Start[] to match 14 | count = 1 15 | X[count] = 1 16 | for i in range(2, n): 17 | if(Start[i] > Finish[X[count]]): 18 | count = count + 1 19 | X[count] = I 20 | return X[1:count] 21 | -------------------------------------------------------------------------------- /src/chapter11searching/ShuffleArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import random 12 | def shuffleArray(A): 13 | n = len(A) 14 | i = n - 1 15 | while i > 0: 16 | j = int((random.random()) % (i + 1)) 17 | tmp = A[j - 1];A[j - 1] = A[j];A[j] = tmp 18 | i -= 1 19 | 20 | A = [1, 3, 5, 6, 2, 4, 6, 8] 21 | shuffleArray(A) 22 | print A 23 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/FiboWithDPTopDown.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | fibTable = {1:1, 2:1} 12 | def Fibo(n): 13 | if n <= 2: 14 | return 1 15 | if n in fibTable: 16 | return fibTable[n] 17 | else: 18 | fibTable[n] = Fibo(n - 1) + Fibo(n - 2) 19 | return fibTable[n] 20 | 21 | print(Fibo(10)) 22 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/ShuffleArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import random 12 | def shuffle_array(A): 13 | n = len(A) 14 | i = n - 1 15 | while i > 0: 16 | j = int((random.random()) % (i + 1)) 17 | tmp = A[j - 1];A[j - 1] = A[j];A[j] = tmp 18 | i -= 1 19 | 20 | A = [1, 3, 5, 6, 2, 4, 6, 8] 21 | shuffle_array(A) 22 | print A 23 | -------------------------------------------------------------------------------- /src/chapter06trees/MirrorOfBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MirrorOfBinaryTree(root): 12 | if(root != None): 13 | MirrorOfBinaryTree(root.left) 14 | MirrorOfBinaryTree(root.right) 15 | 16 | # swap the pointers in this node 17 | temp = root.left 18 | root.left = root.right 19 | root.right = temp 20 | 21 | return root 22 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckPairwiseSortedness.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def checkPairwiseSorted(A): 12 | n = len(A) 13 | if (n == 0 or n == 1): 14 | return 1 15 | for i in range(0, n - 1, 2): 16 | if (A[i] > A[i + 1]): 17 | return 0 18 | return 1 19 | 20 | 21 | A = [34, 48, 10, 13, 2, 80, 30, 23] 22 | print checkPairwiseSorted(A) 23 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/CatalanWithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CatalanNumber(n): 12 | catalan = [1, 1] + [0] * n 13 | for i in range(2, n + 1): 14 | for j in range(n): 15 | catalan[i] += catalan[j] * catalan[i - j - 1] 16 | return catalan[n] 17 | 18 | print CatalanNumber(4) 19 | -------------------------------------------------------------------------------- /src/chapter04stacks/FindingSpansNotEfficient.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findingSpans(A): 12 | s = [None] * len(A) 13 | for i in range(0, len(A)): 14 | j = 1 15 | while j <= i and A[i] > A[i - j]: 16 | j = j + 1 17 | s[i] = j 18 | print s 19 | 20 | findingSpans(['6', '3', '4', '5', '2']) 21 | -------------------------------------------------------------------------------- /src/chapter11searching/LinearSearch.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | key = "Data Structure and Algorithmic Thinking with Python" 12 | 13 | i = 0 14 | while i < len(name_list) and name_list[i] != key: 15 | i += 1 16 | 17 | if i < len(name_list): 18 | print("The name is at position", i) 19 | else: 20 | print("The name was not in the list.") 21 | -------------------------------------------------------------------------------- /src/chapter11searching/PrintTwoRepeatedElementsBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def PrintTwoRepeatedElementsBruteForce(A): 13 | n = len(A) 14 | for i in range(0, n): 15 | for j in range(i + 1, n): 16 | if(A[i] == A[j]): 17 | print A[i] 18 | 19 | 20 | A = [3, 5, 7, 4, 2, 4, 2, 1, 9] 21 | PrintTwoRepeatedElementsBruteForce(A) 22 | -------------------------------------------------------------------------------- /src/chapter11searching/RemoveDuplicatesWithSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def RemoveDuplicates(A): 12 | A.sort() 13 | print A 14 | j = 0 15 | for i in range(1, len(A)): 16 | if (A[j] != A[i]): 17 | j += 1 18 | A[j] = A[i] 19 | 20 | 21 | print A[:j + 1] 22 | 23 | A = [54, 31, 93, 54, 77, 31, 44, 55, 93] 24 | RemoveDuplicates(A) 25 | -------------------------------------------------------------------------------- /src/chapter04stacks/IsPalindrome2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def isPalindrome(A): 12 | i = 0 13 | j = len(A) - 1 14 | while (i < j and A[i] == A[j]): 15 | i += 1 16 | j -= 1 17 | if (i < j): 18 | print("Not a Palindrome") 19 | return 0 20 | else: 21 | print("Palindrome") 22 | return 1 23 | 24 | isPalindrome(['m', 'a', 'd', 'a', 'm']) 25 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/NumberOfTrailingZerosOfFactorialNumber.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def number_of_trailing_zeros_of_factorial_number(n): 12 | count = 0 13 | if(n < 0): 14 | return -1 15 | i = 5 16 | while n / i > 0: 17 | count += n / i 18 | i *= 5 19 | return count 20 | 21 | print number_of_trailing_zeros_of_factorial_number(100) 22 | -------------------------------------------------------------------------------- /src/chapter06trees/AreMirrors.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def AreMirrors(root1, root2): 12 | if(root1 == None and root2 == None): 13 | return 1 14 | if(root1 == None or root2 == None): 15 | return 0 16 | if(root1.data != root2.data): 17 | return 0 18 | else: 19 | return AreMirrors(root1.left, root2.right) and AreMirrors(root1.right, root2.left) 20 | -------------------------------------------------------------------------------- /src/chapter06trees/AugmentedTreesKthSmallest.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def KthSmallest (X, K): 12 | r = X.left.size + 1 # Assume size property is added to node 13 | if(K == r): 14 | return X 15 | if(K < r): 16 | return KthSmallest (X.left, K) 17 | if(K > r): 18 | return KthSmallest (X.right, K - r) 19 | 20 | -------------------------------------------------------------------------------- /src/chapter10sorting/InsertionSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Insertionsort(A): 12 | for i in range(1, len(A)): 13 | tmp = A[i] 14 | k = i 15 | while k > 0 and tmp < A[k - 1]: 16 | A[k] = A[k - 1] 17 | k -= 1 18 | A[k] = tmp 19 | 20 | A = [54, 26, 93, 17, 77, 31, 44, 55, 20] 21 | Insertionsort(A) 22 | print(A) 23 | -------------------------------------------------------------------------------- /src/chapter11searching/RemoveAdjacentRepeats.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def removeAdjacentRepeats(nums): 12 | i = 1 13 | while i < len(nums): 14 | if nums[i] == nums[i - 1]: 15 | nums.pop(i) 16 | i -= 1 17 | i += 1 18 | return nums 19 | 20 | nums = ["A", "B", "C", "C", "C", "C", "B", "A"] 21 | print removeAdjacent(nums) 22 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/ShuffleCards.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import random 12 | def shuffle(cards): 13 | max = len(cards) - 1 14 | while max != 0: 15 | r = random.randint(0, max) 16 | cards[r], cards[max] = cards[max], cards[r] 17 | max = max - 1 18 | return cards 19 | 20 | actual = range(1, 53) 21 | shuffle(actual) 22 | -------------------------------------------------------------------------------- /src/chapter11searching/FindMissingNumberBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FindMissingNumber(A): 12 | n = len(A) 13 | for i in range(1, n + 1): 14 | found = 0 15 | for j in range(0, n): 16 | if(i == A[j]): 17 | found = 1 18 | if found == 0: 19 | print "Missing number is ", i 20 | 21 | A = [8, 2, 1, 4, 6, 5, 7, 9] 22 | FindMissingNumber(A) 23 | -------------------------------------------------------------------------------- /src/chapter11searching/FindNonrepeatedCharacterBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findNonrepeated(A): 12 | n = len(A) 13 | for i in range(0, n): 14 | repeated = 0 15 | for j in range(0, n): 16 | if(i != j and A[i] == A[j]): 17 | repeated = 1 18 | if repeated == 0: 19 | return A[i] 20 | return 21 | 22 | print findNonrepeated("careermonk") 23 | -------------------------------------------------------------------------------- /src/chapter11searching/TwoElementsWithSumKBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def twoElementsWithSumKBruteForce(A, K): 12 | n = len(A) 13 | for i in range(0, n): 14 | for j in range(i + 1, n): 15 | if(A[i] + A[j] == K): 16 | return 1 17 | return 0 18 | 19 | A = [1, 4, 45, 6, 10, -8] 20 | A.sort() 21 | print twoElementsWithSumKBruteForce(A, 111) 22 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/CatalanWithFormula.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | catalan = [] 12 | 13 | # 1st term is 1 14 | catalan.append(1) 15 | 16 | for i in range (1, 1001): 17 | x = catalan[i - 1] * (4 * i - 2) / (i + 1) 18 | catalan.append(x) 19 | 20 | 21 | def CatalanNumber(n): 22 | return catalan[n] 23 | 24 | print CatalanRecursive(4) 25 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/longest_common_subsequence_recursive.py: -------------------------------------------------------------------------------- 1 | def LCS(X, Y): 2 | if not X or not Y: 3 | return "" 4 | x, m, y, n = X[0], X[1:], Y[0], Y[1:] 5 | if x == y: 6 | return x+LCS(m, n) 7 | else: 8 | # Use key=len to select the maximum string in a list efficiently 9 | return max(LCS (X, n), LCS(m, Y), key=len) 10 | 11 | print "Longest common subsequence: ", LCS('ABCBDAB', 'BDCABA') 12 | 13 | def LCS_length(X, Y): 14 | if not X or not Y: 15 | return 0 16 | x, m, y, n = X[0], X[1:], Y[0], Y[1:] 17 | if x == y: 18 | return 1+LCS_length(m, n) 19 | else: 20 | # Use key=len to select the maximum string in a list efficiently 21 | return max(LCS_length(X, n), LCS_length(m, Y)) 22 | 23 | print "Longest common subsequence length: ", LCS_length('ABCBDAB', 'BDCABA') 24 | -------------------------------------------------------------------------------- /src/chapter01introduction/SqrtComplextity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | i = s = 1 14 | while s < n: 15 | i = i + 1 16 | s = s + i 17 | print("*") 18 | 19 | 20 | function(20) 21 | 22 | def Function2(n): 23 | i = 1 24 | count = 0 25 | while i * i < n: 26 | count = count + 1 27 | i = i + 1 28 | print(count) 29 | 30 | Function2(20) 31 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/FindNonrepeatedCharacterBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findNonrepeated(A): 12 | n = len(A) 13 | for i in range(0, n): 14 | repeated = 0 15 | for j in range(0, n): 16 | if(i != j and A[i] == A[j]): 17 | repeated = 1 18 | if repeated == 0: 19 | return A[i] 20 | return 21 | 22 | print findNonrepeated("careermonk") 23 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/DeleteLinkedListDuplicates.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def deleteLinkedListDuplicates(self): 12 | current = self.head; 13 | while current != None and current.next != None: 14 | if current.get_data() == current.get_next().get_data(): 15 | current.set_next(current.get_next().get_next()) 16 | else: 17 | current = current.get_next() 18 | return head 19 | -------------------------------------------------------------------------------- /src/chapter01introduction/ComplexityWithBreakStatement.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | count = 0 14 | for i in range(n / 2, n): # Outer loop execute n/2 times 15 | j = 1 16 | count = count + 1 17 | while j + n / 2 <= n: # Middle loop has break 18 | break 19 | j = j * 2 20 | count = count + 1 21 | 22 | print (count) 23 | 24 | function(20) 25 | 26 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/ReverseInPairs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def reverseInPairs(self) : 12 | temp = self.head 13 | while None != temp and None != temp.get_next(): 14 | self.swapData(temp, temp.get_next()) 15 | temp = temp.get_next().get_next() 16 | 17 | def swapData(self, a, b): 18 | tmp = a.get_data() 19 | a.set_data(b.get_data()) 20 | b.set_data(tmp) 21 | -------------------------------------------------------------------------------- /src/chapter06trees/SortedArrayToBST.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def sortedArrayToBST(root, array): 12 | length = len(array) 13 | if length == 0: 14 | return None 15 | if length == 1: 16 | return TreeNode(array[0]) 17 | root = BSTNode(array[length / 2]) 18 | root.left = sortedArrayToBST(array[:length / 2]) 19 | root.right = sortedArrayToBST(array[length / 2 + 1:]) 20 | return root 21 | -------------------------------------------------------------------------------- /src/chapter10sorting/SortListByFrequency.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | myString = "We want to get the counts for each letter in this sentence" 12 | counts = {} 13 | 14 | for letter in myString: 15 | counts[letter] = counts.get(letter, 0) + 1 16 | print counts 17 | 18 | sortedKeys = sorted(counts.keys(), key=lambda x: counts[x]) 19 | for k in sortedKeys: 20 | print k , "-->" , counts[k] 21 | -------------------------------------------------------------------------------- /src/chapter11searching/planting.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Oct 22, 2018 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def planting(A, K): 12 | counter = 0 13 | for i in range(0,len(A)): 14 | if (A[i] == 0 and (i == 0 or A[i-1] ==0) and ( i == len(A)-1 or A[i+1] == 0)): 15 | A[i] = 1 16 | counter += 1 17 | if counter == K: 18 | return True, A 19 | return False 20 | 21 | print planting([1,0,0,0,1,0,0], 2) 22 | print planting([1,0,0,0,1,0,0], 3) 23 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/FindIntersectingNodeUsingHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findIntersectingNode(self, list1, list2): 12 | intersect = {} 13 | t = list1 14 | while None != t: 15 | intersect[t] = True 16 | t = t.get_next() 17 | 18 | # first duplicate is intersection 19 | t = list2 20 | while None != t: 21 | if None != intersect.get(t): 22 | return t 23 | t = t.get_next() 24 | return None 25 | -------------------------------------------------------------------------------- /src/chapter06trees/BSTFind.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | # Search the key from node, iteratively 12 | def Find(self, root, data): 13 | currentNode = root 14 | while currentNode: 15 | if data == currentNode.get_data(): 16 | return currentNode 17 | if key < currentNode.get_data(): 18 | currentNode = currentNode.getLeft() 19 | else: 20 | currentNode = currentNode.getRight() 21 | return None 22 | -------------------------------------------------------------------------------- /src/chapter11searching/RearrangeArrayElementsA1B1A2B2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def rearrangeArrayElementsA1B1A2B2(A): 12 | n = len(A) // 2 13 | i = 0; q = 1; k = n 14 | while (i < n): 15 | 16 | j = k 17 | while j > i + q: 18 | A[j], A[j - 1] = A[j - 1], A[j] 19 | j -= 1 20 | i += 1; k += 1; q += 1 21 | 22 | A = [1, 3, 5, 6, 2, 4, 6, 8] 23 | rearrangeArrayElementsA1B1A2B2(A) 24 | print A 25 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckDuplicatesSorting.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckDuplicatesSorting(A): 12 | A.sort() 13 | for i in range(0, len(A) - 1): 14 | if(A[i] == A[i + 1]): 15 | print("Duplicates exist:", A[i]) 16 | return 17 | print("No duplicates in given array.") 18 | 19 | A = [33, 2, 10, 20, 22, 32] 20 | CheckDuplicatesSorting(A) 21 | A = [3, 2, 1, 2, 2, 3] 22 | CheckDuplicatesSorting(A) 23 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/FactorialwithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | factTable = {} 12 | 13 | def factorial(n): 14 | try: 15 | return factTable[n] 16 | except KeyError: 17 | if n == 0: 18 | factTable[0] = 1 19 | return 1 20 | else: 21 | factTable[n] = n * factorial(n - 1) 22 | return factTable[n] 23 | 24 | print(factorial(10)) 25 | -------------------------------------------------------------------------------- /src/chapter01introduction/NCubeLognComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | if (n < 2): # Constant time 14 | return 15 | else: 16 | counter = 0 # Constant time 17 | for i in range(1, 8): # This loop executes 8 times with n value half in every call 18 | function (n / 2) 19 | for i in range(1, n ** 3): # This loop executes n^3 times with constant time loop 20 | counter = counter + 1 -------------------------------------------------------------------------------- /src/chapter11searching/MaxRepititionsEfficient.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxRepititionsEfficient(A): 12 | n = len(A) 13 | max = 0 14 | for i in range(0, len(A)): 15 | A[A[i] % n] += n 16 | for i in range(0, len(A)): 17 | if(A[i] / n > max): 18 | max = A[i] / n 19 | maxIndex = i 20 | print maxIndex, "repeated for ", max, " times" 21 | A = [3, 2, 2, 3, 2, 2, 2, 3, 3] 22 | MaxRepititionsEfficient(A) 23 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckDuplicatesNegationTechnique.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import math 12 | def CheckDuplicatesNegationTechnique(A): 13 | for i in range(0, len(A)): 14 | if(A[abs(A[i])] < 0): 15 | print("Duplicates exist:", A[i]) 16 | return 17 | else: 18 | A[abs(A[i])] *= -1 19 | 20 | print("No duplicates in given array.") 21 | 22 | A = [3, 2, 1, 2, 2, 3] 23 | CheckDuplicatesNegationTechnique(A) 24 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/LongestCommonSubsequenceWithoutDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def LCSLength(X, Y): 12 | if not X or not Y: 13 | return "" 14 | x, m, y, n = X[0], X[1:], Y[0], Y[1:] 15 | if x == y: 16 | return x + LCSLength(m, n) 17 | else: 18 | return max(LCSLength(X, n), LCSLength(m, Y), key=len) 19 | 20 | print (LCSLength('thisisatest', 'testingLCS123testing')) 21 | -------------------------------------------------------------------------------- /src/chapter01introduction/NLogSquareComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | count = 0 14 | for i in range(n / 2, n): # Outer loop execute n/2 times 15 | j = 1 16 | while j + n / 2 <= n: # Middle loop executes logn times 17 | k = 1 18 | while k <= n: # Inner loop execute logn times 19 | count = count + 1 20 | k = k * 2 21 | j = j * 2 22 | 23 | print (count) 24 | 25 | function(20) 26 | -------------------------------------------------------------------------------- /src/chapter01introduction/NSquareLogNComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | count = 0 14 | for i in range(n / 2, n): # Outer loop execute n/2 times 15 | j = 1 16 | while j + n / 2 <= n: # Middle loop executes n/2 times 17 | k = 1 18 | while k <= n: # Inner loop execute logn times 19 | count = count + 1 20 | k = k * 2 21 | j = j + 1 22 | 23 | print (count) 24 | 25 | function(20) 26 | -------------------------------------------------------------------------------- /src/chapter06trees/FillNextSiblings.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def fillNextSiblings(root): 12 | if (root == None): 13 | return 14 | 15 | if root.left: 16 | root.left.nextSibling = root.right 17 | 18 | if roo.tright: 19 | if root.nextSibling: 20 | root.right.nextSibling = root.nextSibling.left 21 | else: 22 | root.right.nextSibling = None 23 | 24 | fillNextSiblings(root.left) 25 | fillNextSiblings(root.right) 26 | -------------------------------------------------------------------------------- /src/chapter11searching/FirstRepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def firstRepeatedChar(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | print("the first repeated character is: %s" % (char)) 17 | return char 18 | elif char != " ": 19 | table[char] = 1 20 | else: 21 | table[char] = 0 22 | return 23 | 24 | print firstRepeatedChar("careermonk") 25 | -------------------------------------------------------------------------------- /src/chapter11searching/FrequencyCounter.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def frequencyCounter(A): 12 | table = {} # hash 13 | for element in A: 14 | if element in table: 15 | table[element] += 1 16 | elif element != " ": 17 | table[element] = 1 18 | else: 19 | table[element] = 0 20 | for element in A: 21 | print element, "--->", table[element] 22 | 23 | A = [10, 1, 9, 4, 7, 6, 5, 22, 13, 2, 1] 24 | frequencyCounter(A) 25 | -------------------------------------------------------------------------------- /src/chapter11searching/MajorityElement.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def majorityElement(A): 12 | count = 0 13 | element = -1 14 | n = len(A) 15 | if n == 0: 16 | return 17 | for i in range(0, n - 1): 18 | if(count == 0) : 19 | element = A[i] 20 | count = 1 21 | elif(element == A[i]): 22 | count += 1 23 | else: 24 | count -= 1 25 | return element 26 | 27 | A = [7, 3, 2, 3, 3, 6, 3 ] 28 | print majorityElement(A) 29 | -------------------------------------------------------------------------------- /src/chapter11searching/pivot.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Oct 22, 2018 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findPivot1(A): 12 | for i in range(len(A)): 13 | leftSum = sum(A[:i]) 14 | rightSum = sum(A[i+1:]) 15 | if leftSum == rightSum: 16 | return A[i] 17 | 18 | def findPivot2(A): 19 | S= sum(A) 20 | leftSum = 0 21 | for i in range(len(A)): 22 | if leftSum == S-A[i]-leftSum: 23 | return A[i] 24 | leftSum += A[i] 25 | 26 | print findPivot2([12,6,9,3,5,2,1,9,10]) 27 | -------------------------------------------------------------------------------- /src/chapter12selectionalgorithms/FindSmallestAndLargestInArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FindSmallestAndLargestInArray(A): 12 | max = 0 13 | min = 0 14 | for number in A: 15 | if number > max: 16 | max = number 17 | elif number < min: 18 | min = number 19 | 20 | print("Smallest: %d", min) 21 | print("Largest: %d", max) 22 | 23 | FindSmallestAndLargestInArray([2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13]) 24 | -------------------------------------------------------------------------------- /src/chapter14hashing/FirstRepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def firstRepeatedChar(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | print("the first repeated character is: %s" % (char)) 17 | return char 18 | elif char != " ": 19 | table[char] = 1 20 | else: 21 | table[char] = 0 22 | return 23 | 24 | print firstRepeatedChar("careermonk") 25 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckDuplicatesBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckDuplicatesBruteForce(A): 12 | for i in range(0, len(A)): 13 | for j in range(i + 1, len(A)): 14 | if(A[i] == A[j]): 15 | print("Duplicates exist:", A[i]) 16 | return; 17 | print("No duplicates in given array.") 18 | 19 | A = [3, 2, 10, 20, 22, 32] 20 | CheckDuplicatesBruteForce(A) 21 | A = [3, 2, 1, 2, 2, 3] 22 | CheckDuplicatesBruteForce(A) 23 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/FirstRepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def firstRepeatedChar(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | print("the first repeated character is: %s" % (char)) 17 | return char 18 | elif char != " ": 19 | table[char] = 1 20 | else: 21 | table[char] = 0 22 | return 23 | 24 | print firstRepeatedChar("careermonk") 25 | -------------------------------------------------------------------------------- /src/chapter11searching/FirstRepeatedChar.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FirstRepeatedChar (str): 12 | size = len(str) 13 | count = [0] * (256) 14 | for i in range(size): 15 | if(count[ord(str[i])] == 1): 16 | print str[i] 17 | break 18 | else: 19 | count[ord(str[i])] += 1 20 | if(i == size): 21 | print "No Repeated Characters" 22 | return 0 23 | 24 | FirstRepeatedChar(['C', 'a', 'r', 'e', 'e', 'r', 'm', 'o', 'n', 'k']) 25 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/PetrolStationsDPProblem.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def canCompleteTour(self, petrol, cost): 12 | minVal = float("inf") 13 | minPos = -1 14 | petrolTillNow = 0 15 | for i in range(0, len(petrol)): 16 | petrolTillNow += petrol[i] - cost[i] 17 | if petrolTillNow < minVal: 18 | minVal = petrolTillNow 19 | minPos = i 20 | if petrolTillNow >= 0: 21 | return (minPos + 1) % len(petrol) 22 | return -1 23 | -------------------------------------------------------------------------------- /src/chapter02recursionandbacktracking/KBitSequences.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def range_to_list(k): 13 | result = [] 14 | for i in range(0, k): 15 | result.append(str(i)) 16 | return result 17 | 18 | def base_k_strings(n, k): 19 | if n == 0: return [] 20 | if n == 1: return range_to_list(k) 21 | return [ digit + bitstring for digit in base_k_strings(1, k) for bitstring in base_k_strings(n - 1, k)] 22 | print base_k_strings(4, 3) 23 | -------------------------------------------------------------------------------- /src/chapter06trees/TrimBST.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def trimBST(root, minVal, maxVal): 12 | if not root: 13 | return 14 | root.setLeft(trimBST(root.getLeft(), minVal, maxVal)) 15 | root.setRight(trimBST(root.getRight(), minVal, maxVal)) 16 | if minVal <= root.get_data() <= maxVal: 17 | return root 18 | if root.get_data() < minVal: 19 | return root.getRight() 20 | if root.get_data() > maxVal: 21 | return root.getLeft() 22 | 23 | -------------------------------------------------------------------------------- /src/chapter10sorting/BubbleSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BubbleSort(A): 12 | for i in range(len(A)): 13 | for k in range(len(A) - 1, i, -1): 14 | if (A[k] < A[k - 1]): 15 | swap(A, k, k - 1) 16 | 17 | def swap(A, x, y): 18 | tmp = A[x] 19 | A[x] = A[y] 20 | A[y] = tmp 21 | 22 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 23 | BubbleSort(A) 24 | print(A) 25 | -------------------------------------------------------------------------------- /src/chapter11searching/MaxIndexDifferenceBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def maxIndexDiff(A): 12 | maxDiff = -1 13 | maxJ = maxI = -1 14 | n = len(A) 15 | for i in range(0, n): 16 | j = n - 1 17 | while(j > i): 18 | if(A[j] > A[i] and maxDiff < (j - i)): 19 | maxDiff = j - i 20 | maxI = i 21 | maxJ = j 22 | j -= 1 23 | return maxDiff, maxI, maxJ 24 | 25 | A = [34, 8, 10, 3, 2, 80, 30, 33, 1] 26 | print maxIndexDiff(A) 27 | -------------------------------------------------------------------------------- /src/chapter10sorting/SeletionSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def SelectionSort(A): 12 | for i in range(len(A)): 13 | least = i 14 | for k in range(i + 1 , len(A)): 15 | if A[k] < A[least]: 16 | least = k 17 | 18 | swap(A, least, i) 19 | 20 | 21 | def swap(A, x, y): 22 | temp = A[x] 23 | A[x] = A[y] 24 | A[y] = temp 25 | 26 | 27 | A = [54, 26, 93, 17, 77, 31, 44, 55, 20] 28 | SelectionSort(A) 29 | print(A) 30 | -------------------------------------------------------------------------------- /src/chapter11searching/SeparateZerosAndOnes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def separateZerosAndOnes(A): 12 | left = 0; right = len(A) - 1 13 | while(left < right): 14 | while(A[left] == 0 and left < right): 15 | left += 1 16 | while(A[right] == 1 and left < right): 17 | right -= 1 18 | if(left < right): 19 | A[left], A[right] = A[right], A[left] 20 | left += 1 21 | right -= 1 22 | A = [1, 1, 0, 0, 1, 0, 1] 23 | separateZerosAndOnes(A) 24 | print A 25 | -------------------------------------------------------------------------------- /src/chapter01introduction/RecursiveNComplexity.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | count = 0 13 | def function(n): 14 | global count 15 | count = 1 16 | if n <= 0: 17 | return 18 | for i in range(1, n): 19 | count = count + 1 20 | n = n // 2; 21 | function(n) 22 | print count 23 | 24 | function(200) 25 | 26 | def Function2(n): 27 | if n <= 0: 28 | return 29 | print ("*") 30 | Function2(n / 2) 31 | Function2(n / 2) 32 | print ("*") 33 | 34 | function(20) 35 | -------------------------------------------------------------------------------- /src/chapter11searching/SeparateODDAndEvenNumbers.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def separateEvenOdd(A): 12 | left = 0; right = len(A) - 1 13 | while(left < right): 14 | while(A[left] % 2 == 0 and left < right): 15 | left += 1 16 | while(A[right] % 2 == 1 and left < right): 17 | right -= 1 18 | if(left < right): 19 | A[left], A[right] = A[right], A[left] 20 | left += 1 21 | right -= 1 22 | A = [12, 34, 45, 9, 8, 90, 3] 23 | separateEvenOdd(A) 24 | print A 25 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/NumberOfConnectedComponents.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | class Solution(object): 12 | def numberOfConnectedComponents(self, head, S): 13 | s = set(S) 14 | current = head 15 | result = 0 16 | while current: 17 | if (current.data in s and 18 | getattr(current.next, 'data', None) not in s): 19 | ans += 1 20 | current = current.next 21 | 22 | return result 23 | 24 | -------------------------------------------------------------------------------- /src/chapter06trees/TreeCompressionBST.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import sys 12 | def TreeCompression(root, previousNodeData): 13 | if(not root): 14 | return None 15 | TreeCompression(root.left, previousNode) 16 | if(previousNodeData == -sys.maxint): 17 | previousNodeData = root.data 18 | free(root) 19 | 20 | if(previousNodeData != -sys.maxint): # Process current node 21 | root.data2 = previousNodeData 22 | return TreeCompression(root.right, previousNode) 23 | 24 | -------------------------------------------------------------------------------- /src/chapter11searching/PrintTwoRepeatedElementsHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def PrintTwoRepeatedElementsHash(A): 12 | table = {} # hash 13 | for element in A: 14 | if element in table: 15 | table[element] += 1 16 | elif element != " ": 17 | table[element] = 1 18 | else: 19 | table[element] = 0 20 | 21 | for element in A: 22 | if table[element] == 2: 23 | print element 24 | 25 | A = [3, 5, 7, 4, 2, 4, 2, 1, 9] 26 | PrintTwoRepeatedElementsHash(A) 27 | -------------------------------------------------------------------------------- /src/chapter11searching/RemoveDuplicatesBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def RemoveDuplicates(A): 12 | m = 0 13 | for i in range(0, len(A)): 14 | if (not elem(A, m, A[i])): 15 | A[m] = A[i] 16 | m += 1 17 | return m 18 | 19 | def elem(A, n, e): 20 | for i in range(0, n): 21 | if (A[i] == e): 22 | return 1 23 | return 0 24 | 25 | A = [54, 26, 93, 54, 77, 31, 44, 55, 20] 26 | RemoveDuplicates(A) 27 | print A 28 | -------------------------------------------------------------------------------- /src/chapter11searching/ThreeElementsWithSumKBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def threeElementsWithSumKBruteForce(A, K): 12 | n = len(A) 13 | for i in range(0, n - 2): 14 | for j in range(i + 1, n - 1): 15 | for k in range(j + 1, n): 16 | if(A[i] + A[j] + A[k] == K): 17 | print "yes-->", A[i], " + ", A[j], " + ", A[k], " = ", K 18 | return 1 19 | return 0 20 | A = [1, 6, 45, 4, 10, 18] 21 | A.sort() 22 | threeElementsWithSumKBruteForce(A, 22) 23 | -------------------------------------------------------------------------------- /src/chapter11searching/MaxRepititionsBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxRepititionsBruteForce(A): 12 | n = len(A) 13 | count = max = 0 14 | for i in range(0, n): 15 | count = 1 16 | for j in range(0, n): 17 | if(i != j and A[i] == A[j]): 18 | count += 1 19 | if max < count: 20 | max = count 21 | maxRepeatedElement = A[i] 22 | print maxRepeatedElement, "repeated for ", max 23 | 24 | A = [3, 2, 1, 2, 2, 3, 2, 1, 3] 25 | MaxRepititionsBruteForce(A) 26 | -------------------------------------------------------------------------------- /src/chapter10sorting/BubbleSortImproved.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BubbleSort(A): 12 | swapped = 1 13 | for i in range(len(A)): 14 | if (swapped == 0): 15 | return 16 | 17 | for k in range(len(A) - 1, i, -1): 18 | if (A[k] < A[k - 1]): 19 | swap(A, k, k - 1) 20 | swapped = 1 21 | 22 | def swap(A, x, y): 23 | temp = A[x] 24 | A[x] = A[y] 25 | A[y] = temp 26 | 27 | 28 | A = [127, 220, 246, 277, 321, 454, 534, 565, 933] 29 | BubbleSort(A) 30 | print(A) 31 | -------------------------------------------------------------------------------- /src/chapter10sorting/Create SortedSquaredArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def sortedSquaredArray(A): 12 | result = [] 13 | for i in range(len(A)): 14 | result.append(A[i]*A[i]) 15 | result.sort() 16 | return result 17 | 18 | A = [-6, -4, 1, 2, 3, 5] 19 | print sortedSquaredArray(A) 20 | 21 | #Second approach 22 | def sortedSquaredArray(A): 23 | return sorted([i**2 for i in A]) 24 | 25 | A = [-6, -4, 1, 2, 3, 5] 26 | print sortedSquaredArray(A) 27 | -------------------------------------------------------------------------------- /src/chapter11searching/MoveSpacesToEnd.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def moveSpacesToEnd(A): 12 | n = len(A) - 1 13 | datalist = list(A) 14 | count = i = 0 15 | for i in range(i, n): 16 | if(not datalist[i].isspace()): 17 | datalist[count] = datalist[i] 18 | count += 1 19 | 20 | while(count <= n): 21 | datalist[count] = ' ' 22 | count += 1 23 | A = ''.join(datalist) 24 | return A 25 | A = "move these spaces to beginning" 26 | print A, "\n", moveSpacesToEnd(A) 27 | 28 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/DLLToBST.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def DLLtoBalancedBST(head): 12 | if(not head or not head.next): 13 | return head 14 | temp = FindMiddleNode(head) # Refer Linked Lists chapter for this function. We can use two-pointer logic to find the middle node 15 | p = head 16 | while(p.next != temp): 17 | p = p.next 18 | p.next = None 19 | q = temp.next 20 | temp.next = None 21 | temp.prev = DLLtoBalancedBST(head) 22 | temp.next = DLLtoBalancedBST(q) 23 | return temp 24 | -------------------------------------------------------------------------------- /src/chapter06trees/DLLToBST.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def DLLtoBalancedBST(head): 12 | if(not head or not head.next): 13 | return head 14 | temp = FindMiddleNode(head) # Refer Linked Lists chapter for this function. We can use two-pointer logic to find the middle node 15 | p = head 16 | while(p.next != temp): 17 | p = p.next 18 | p.next = None 19 | q = temp.next 20 | temp.next = None 21 | temp.prev = DLLtoBalancedBST(head) 22 | temp.next = DLLtoBalancedBST(q) 23 | return temp 24 | -------------------------------------------------------------------------------- /src/chapter11searching/RemoveCharsFromString.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def RemoveChars(str, removeTheseChars): 12 | table = {} # hash 13 | temp = [] 14 | # set true for all characters to be removed 15 | for char in removeTheseChars.lower(): 16 | table[char] = 1 17 | index = 0 18 | for char in str.lower(): 19 | if char in table: 20 | continue 21 | else: 22 | temp.append(char) 23 | index += 1 24 | return "".join(temp) 25 | 26 | print RemoveChars("careermonk", "e") 27 | 28 | -------------------------------------------------------------------------------- /src/chapter11searching/TwoElementsWithSumKEfficientWithSorting.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def pair_sum_k_sorting(A, K): 12 | left = 0 13 | right = len(A) - 1; 14 | while(left < right): 15 | if(A[left] + A[right] == K): 16 | return 1 17 | elif(A[left] + A[right] < K): 18 | left += 1 19 | else: 20 | right -= 1 21 | return 0 22 | 23 | A = [1, 4, 45, 6, 10, -8] 24 | A.sort() 25 | print pair_sum_k_sorting(A, 11) 26 | -------------------------------------------------------------------------------- /src/chapter06trees/SuccessorPredessor.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | # Successror of a node in BST 12 | def successorBST(root): 13 | temp = None 14 | if root.getRight(): 15 | temp = root.getRight() 16 | while temp.getLeft(): 17 | temp = s.getLeft() 18 | return temp 19 | 20 | # Predecessor of a node in BST 21 | def predecessorBST(root): 22 | temp = None 23 | if root.getLeft(): 24 | temp = root.getLeft() 25 | while temp.getRight(): 26 | temp = temp.getRight() 27 | return temp 28 | -------------------------------------------------------------------------------- /src/chapter11searching/BinarySearchIterative.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchIterative(numbersList, value): 12 | low = 0 13 | high = len(numbersList) - 1 14 | while low <= high: 15 | mid = (low + high) // 2 16 | if numbersList[mid] > value: high = mid - 1 17 | elif numbersList[mid] < value: low = mid + 1 18 | else: return mid 19 | return -1 20 | 21 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 22 | print(BinarySearchIterative(A, 277)) 23 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/RemoveCharsFromString.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def RemoveChars(str, removeTheseChars): 12 | table = {} # hash 13 | temp = [] 14 | # set true for all characters to be removed 15 | for char in removeTheseChars.lower(): 16 | table[char] = 1 17 | index = 0 18 | for char in str.lower(): 19 | if char in table: 20 | continue 21 | else: 22 | temp.append(char) 23 | index += 1 24 | return "".join(temp) 25 | 26 | print RemoveChars("careermonk", "e") 27 | 28 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/SubsetSum.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def positiveSubsetSum(A, X): 12 | # preliminary 13 | if X < 0 or X > sum(A): # T = sum(A) 14 | return False 15 | 16 | # algorithm 17 | subSum = [False] * (X + 1) 18 | subSum[0] = True 19 | p = 0 20 | while not subSum[X] and p < len(A): 21 | a = A[p] 22 | q = X 23 | while not subSum[X] and q >= a: 24 | if not subSum[q] and subSum[q - a]: 25 | subSum[q] = True 26 | q -= 1 27 | p += 1 28 | return subSum[X] 29 | -------------------------------------------------------------------------------- /src/chapter05queues/MinSlidingWindowWithDequeue.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | from collections import deque 12 | 13 | def MinSlidingWindow(A, k): 14 | D = deque() 15 | res, i = [], 0 16 | for i in xrange(len(A)): 17 | while D and D[-1][0] >= A[i]: 18 | D.pop() 19 | D.append((A[i], i + k - 1)) 20 | if i >= k - 1: res.append(D[0][0]) 21 | if i == D[0][1]: D.popleft() 22 | return res 23 | 24 | print MinSlidingWindow([4, 3, 2, 1, 5, 7, 6, 8, 9], 3) 25 | -------------------------------------------------------------------------------- /src/chapter11searching/FindMissingNumberFromGivenRange.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import sys 12 | def findMissingNumberFromGivenRange(A, X, Y): 13 | n = len(A) 14 | S = [-sys.maxint] * (n) 15 | missingNum = -sys.maxint 16 | for i in range(0, n): 17 | S[A[i] - X] = A[i] 18 | for i in range(0, n): 19 | if(S[i] == -sys.maxint): 20 | missingNum = i + X 21 | break 22 | return missingNum 23 | A = [10, 16, 14, 12, 11, 10, 13 , 15, 17, 12, 19] 24 | print findMissingNumberFromGivenRange(A, 10, 20) 25 | -------------------------------------------------------------------------------- /src/chapter11searching/FindNonrepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findNonrepeated(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | elif char != " ": 17 | table[char] = 1 18 | else: 19 | table[char] = 0 20 | 21 | for char in A.lower(): 22 | if table[char] == 1: 23 | print("the first non repeated character is: %s" % (char)) 24 | return char 25 | 26 | return 27 | 28 | print findNonrepeated("careermonk") 29 | -------------------------------------------------------------------------------- /src/chapter14hashing/FindNonrepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findNonrepeated(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | elif char != " ": 17 | table[char] = 1 18 | else: 19 | table[char] = 0 20 | 21 | for char in A.lower(): 22 | if table[char] == 1: 23 | print("the first non repeated character is: %s" % (char)) 24 | return char 25 | 26 | return 27 | 28 | print findNonrepeated("careermonk") 29 | -------------------------------------------------------------------------------- /src/chapter06trees/DepthOfGenericTreeFromArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findDepthInGenericTree(P): 12 | maxDepth = -1 13 | currentDepth = -1 14 | for i in range (0, len(P)): 15 | currentDepth = 0 16 | j = i 17 | while(P[j] != -1): 18 | currentDepth += 1 19 | j = P[j] 20 | if(currentDepth > maxDepth): 21 | maxDepth = currentDepth 22 | 23 | return maxDepth 24 | 25 | P = [-1, 0, 1, 6, 6, 0, 0, 2, 7] 26 | print "Depth of given Generic Tree is:", findDepthInGenericTree(P) 27 | -------------------------------------------------------------------------------- /src/chapter07priorityqueues/MaxSlidingWindowWithHeap.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | from collections import deque 12 | 13 | def MaxSlidingWindow(A, k): 14 | D = deque() 15 | res, i = [], 0 16 | for i in xrange(len(A)): 17 | while D and D[-1][0] <= A[i]: 18 | D.pop() 19 | D.append((A[i], i + k - 1)) 20 | if i >= k - 1: res.append(D[0][0]) 21 | if i == D[0][1]: D.popleft() 22 | return res 23 | 24 | print MaxSlidingWindow([4, 3, 2, 1, 5, 7, 6, 8, 9], 3) 25 | -------------------------------------------------------------------------------- /src/chapter07priorityqueues/MinSlidingWindowWithDequeue.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | from collections import deque 12 | 13 | def MinSlidingWindow(A, k): 14 | D = deque() 15 | res, i = [], 0 16 | for i in xrange(len(A)): 17 | while D and D[-1][0] >= A[i]: 18 | D.pop() 19 | D.append((A[i], i + k - 1)) 20 | if i >= k - 1: res.append(D[0][0]) 21 | if i == D[0][1]: D.popleft() 22 | return res 23 | 24 | print MinSlidingWindow([4, 3, 2, 1, 5, 7, 6, 8, 9], 3) 25 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/BinarySearchIterative.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchIterative(numbersList, value): 12 | low = 0 13 | high = len(numbersList) - 1 14 | while low <= high: 15 | mid = (low + high) // 2 16 | if numbersList[mid] > value: high = mid - 1 17 | elif numbersList[mid] < value: low = mid + 1 18 | else: return mid 19 | return -1 20 | 21 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 22 | print(BinarySearchIterative(A, 277)) 23 | -------------------------------------------------------------------------------- /src/chapter06trees/RootToLeavesTotalSum.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def sumNumbers(self, root): 12 | if not root: 13 | return 0 14 | current = 0 15 | sum = [0] 16 | self.calSum(root, current, sum) 17 | return sum[0] 18 | 19 | def calSum(self, root, current, sum): 20 | if not root: 21 | return 22 | current = current * 10 + root.data 23 | if not root.left and not root.right: 24 | sum[0] += current 25 | return 26 | 27 | self.calSum(root.left, current, sum) 28 | self.calSum(root.right, current, sum) 29 | -------------------------------------------------------------------------------- /src/chapter11searching/PrintTwoRepeatedElementsHash2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def PrintTwoRepeatedElementsHash2(A): 12 | table = {} # hash 13 | for element in A: 14 | # print element 15 | if element in table and table[element] == 1: 16 | print element 17 | table[element] += 1 18 | elif element in table: 19 | table[element] += 1 20 | elif element != " ": 21 | table[element] = 1 22 | else: 23 | table[element] = 0 24 | A = [3, 5, 7, 4, 2, 4, 2, 1, 9] 25 | PrintTwoRepeatedElementsHash2(A) 26 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/FindNonrepeatedCharacterWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findNonrepeated(A): 12 | table = {} # hash 13 | for char in A.lower(): 14 | if char in table: 15 | table[char] += 1 16 | elif char != " ": 17 | table[char] = 1 18 | else: 19 | table[char] = 0 20 | 21 | for char in A.lower(): 22 | if table[char] == 1: 23 | print("the first non repeated character is: %s" % (char)) 24 | return char 25 | 26 | return 27 | 28 | print findNonrepeated("careermonk") 29 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/SubsetSum2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def SubsetSum2(A): 12 | n = len(A) 13 | K = 0 14 | for i in range(0, n): 15 | K += A[i] 16 | A.sort() 17 | T = [0] * (K + 1) 18 | T[0] = 1 19 | R = 0 20 | # process the numbers one by one 21 | for i in range(0, n): 22 | for j in range(R, -1, -1): 23 | if(T[j]): 24 | T[j + A[i]] = 1 25 | R = min(K / 2, R + A[i]) 26 | 27 | return T[K / 2] 28 | 29 | A = [3, 2, 4, 19, 3, 7, 13, 10, 6, 11] 30 | 31 | print SubsetSum2(A) 32 | -------------------------------------------------------------------------------- /src/chapter11searching/TwoElementsWithSumKWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def twoElementsWithSumKWithHash(A, K): 12 | table = {} # hash 13 | for element in A: 14 | if element in table: 15 | table[element] += 1 16 | elif element != " ": 17 | table[element] = 1 18 | else: 19 | table[element] = 0 20 | for element in A: 21 | if K - element in table: 22 | print "yes-->", element, "+", K - element, " = ", K 23 | A = [1, 4, 45, 6, 10, -8] 24 | A.sort() 25 | twoElementsWithSumKWithHash(A, 11) 26 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/StrstrBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def strstrBruteForce(str, pattern): 12 | if not pattern: return 0 13 | for i in range(len(str) - len(pattern) + 1): 14 | stri = i; patterni = 0 15 | while stri < len(str) and patterni < len(pattern) and str[stri] == pattern[patterni]: 16 | stri += 1 17 | patterni += 1 18 | if patterni == len(pattern): return i 19 | return -1 20 | 21 | print strstrBruteForce("xxxxyzabcdabcdefabc", "abc") 22 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/SubsetSumWithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def SubsetSum(A, T): 12 | n = len(A) 13 | M = [[0 for x in range(T + 1)] for x in range(n + 1)] 14 | 15 | M[0][0] = 0 16 | for i in range(0, n + 1): 17 | M[i][0] = 0 18 | for i in range(0, T + 1): 19 | M[0][i] = 0 20 | for i in range(1, n + 1): 21 | for j in range(1, T + 1): 22 | M[i][j] = M[i - 1][j] or (M[i - 1][j - A[i]]) 23 | return M[n][T] 24 | 25 | A = [3, 2, 4, 19, 3, 7, 13, 10, 6, 11] 26 | 27 | print SubsetSum(A, 17) 28 | -------------------------------------------------------------------------------- /src/chapter11searching/MatrixSortedFind.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def matrixFind(matrix, value): 12 | m = len(matrix) 13 | if m == 0: 14 | return 0 15 | 16 | n = len(matrix[0]) 17 | if n == 0: 18 | return 0 19 | 20 | i = 0 21 | j = n - 1 22 | 23 | while i < m and j >= 0: 24 | if matrix[i][j] == value: 25 | return 1 26 | 27 | elif matrix[i][j] < value: 28 | i = i + 1 29 | 30 | else: 31 | j = j - 1 32 | 33 | return 0 34 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/PrintInterleavings.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def PrintInterleavings(str1, str2): 12 | perms = [] 13 | if len(str1) + len(str2) == 1: 14 | return [str1 or str2] 15 | if str1: 16 | for item in PrintInterleavings(str1[1:], str2): 17 | perms.append(str1[0] + item) 18 | if str2: 19 | for item in PrintInterleavings(str1, str2[1:]): 20 | perms.append(str2[0] + item) 21 | return perms 22 | 23 | print PrintInterleavings("AB", "CD") 24 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/LongestIncreasingSubSeq.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def LongestIncreasingSequence(numList): 12 | n = len(numList) 13 | LISTable = [1] 14 | for i in range(1, len(numList))): 15 | LISTable.append(1) 16 | for j in range(i + 1, n): 17 | if numList[i] < numList[j] and LISTable[i] < LISTable[j] + 1: 18 | LISTable[i] = 1 + LISTable[j] 19 | print LISTable 20 | return max(LISTable) 21 | 22 | print LongestIncreasingSequence([3, 2, 6, 4, 5, 1]) 23 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/MatrixSortedFind.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def matrix_find(matrix, value): 12 | m = len(matrix) 13 | if m == 0: 14 | return 0 15 | 16 | n = len(matrix[0]) 17 | if n == 0: 18 | return 0 19 | 20 | i = 0 21 | j = n - 1 22 | 23 | while i < m and j >= 0: 24 | if matrix[i][j] == value: 25 | return 1 26 | 27 | elif matrix[i][j] < value: 28 | i = i + 1 29 | 30 | else: 31 | j = j - 1 32 | 33 | return 0 34 | -------------------------------------------------------------------------------- /src/chapter06trees/LCAInBinaryTree.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def lca(root, alpha, beta): 12 | if not root: return None 13 | if root.value == alpha or root.value == beta: return root 14 | left = lca(root.left, alpha, beta) 15 | right = lca(root.right, alpha, beta) 16 | if left and right: 17 | # alpha & beta are on both sides 18 | return root 19 | else: 20 | # EITHER alpha/beta is on one side 21 | # OR alpha/beta is not in L&R subtrees 22 | return left if left else right 23 | -------------------------------------------------------------------------------- /src/chapter11searching/MaxRepititionsWithSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxRepititionsWithSort(A): 12 | A.sort() 13 | print A 14 | j = 0 15 | count = max = 1 16 | element = A[0] 17 | for i in range(1, len(A)): 18 | if (A[i] == element): 19 | count += 1 20 | if count > max: 21 | max = count 22 | maxRepeatedElement = element 23 | else: 24 | count = 1 25 | element = A[i] 26 | 27 | print maxRepeatedElement, "repeated for ", max 28 | 29 | A = [3, 2, 1, 3, 2, 3, 2, 3, 3] 30 | MaxRepititionsWithSort(A) 31 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/LongestIncreasingSequence2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def LongestIncreasingSequence2(numList): 12 | n = len(numList) 13 | LISTable = [1] 14 | for i in range(1, len(numList))): 15 | LISTable.append(1) 16 | for j in range(i + 1, n): 17 | if numList[i] < numList[j] and LISTable[i] < LISTable[j] + 1: 18 | LISTable[i] = 1 + LISTable[j] 19 | print LISTable 20 | return max(LISTable) 21 | 22 | print LongestIncreasingSequence2([3, 2, 6, 4, 5, 1]) 23 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MaxContigousSumWithNSquare.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxContigousSum(A): 12 | maxSum = 0 13 | n = len(A) 14 | for i in range(1, n): 15 | currentSum = 0 16 | for j in range(i, n): 17 | currentSum += A[j] 18 | if(currentSum > maxSum): 19 | maxSum = currentSum 20 | 21 | return maxSum; 22 | 23 | A = [-2, 3, -16, 100, -4, 5] 24 | print MaxContigousSum(A) 25 | A = [-2, 11, -4, 13, -5, 2 ] 26 | print MaxContigousSum(A) 27 | A = [-15, -23, -476, -3, -292] 28 | print MaxContigousSum(A) 29 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/MergeTwoLists.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def mergeTwoLists(self, list1, list2): 12 | temp = Node() 13 | pointer = temp 14 | while list1 != None and list2 != None: 15 | if list1.get_data() < list2.get_data(): 16 | pointer.set_next(list1) 17 | list1 = list1.get_next() 18 | else: 19 | pointer.set_next(list2) 20 | list2 = list2.get_next() 21 | pointer = pointer.get_next() 22 | if list1 == None: 23 | pointer.set_next(list2) 24 | else: 25 | pointer.set_next(list1) 26 | return temp.get_next() 27 | -------------------------------------------------------------------------------- /src/chapter06trees/PrintPathsRecur.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def sumNumbers(self, root): 12 | if not root: 13 | return 0 14 | current = 0 15 | sum = [0] 16 | self.printPathsRecur(root, current, sum) 17 | return sum[0] 18 | 19 | def printPathsRecur(self, root, current, sum): 20 | if not root: 21 | return 22 | current = current * 10 + root.data 23 | if not root.left and not root.right: 24 | sum[0] += current 25 | return 26 | 27 | self.printPathsRecur(root.left, current, sum) 28 | self.printPathsRecur(root.right, current, sum) 29 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/MergeTwoSortedLists.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def mergeTwoSortedLists(self, list1, list2): 12 | temp = Node(0) 13 | pointer = temp 14 | while list1 != None and list2 != None: 15 | if list1.get_data() < list2.get_data(): 16 | pointer.set_next(list1) 17 | list1 = list1.get_next() 18 | else: 19 | pointer.set_next(list2) 20 | list2 = list2.get_next() 21 | pointer = pointer.get_next() 22 | if list1 == None: 23 | pointer.set_next(list2) 24 | else: 25 | pointer.set_next(list1) 26 | return temp.get_next() 27 | -------------------------------------------------------------------------------- /src/chapter11searching/ReplaceWithNearestGreaterElement.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def replaceWithNearestGreaterElement(A): 12 | nextNearestGreater = float("-inf") 13 | i = j = 0 14 | for i in range(0, len(A) - 1): 15 | nextNearestGreater = float("-inf") 16 | for j in range(i + 1, len(A)): 17 | if A[i] < A[j]: 18 | nextNearestGreater = A[j] 19 | break 20 | print("For the element " + str(A[i]) + ", " + str(nextNearestGreater) + " is the nearest greater element") 21 | 22 | replaceWithNearestGreaterElement([6, 2, 4, 1, 2, 1, 2, 2, 10]) 23 | -------------------------------------------------------------------------------- /src/chapter05queues/Dequeue.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | class Deque: 12 | def __init__(self): 13 | self.items = [] 14 | 15 | def isEmpty(self): 16 | return self.items == [] 17 | 18 | def addFront(self, item): 19 | self.items.append(item) 20 | 21 | def addRear(self, item): 22 | self.items.insert(0, item) 23 | 24 | def removeFront(self): 25 | return self.items.pop() 26 | 27 | def removeRear(self): 28 | return self.items.pop(0) 29 | 30 | def size(self): 31 | return len(self.items) 32 | -------------------------------------------------------------------------------- /src/chapter10sorting/CheckWhoWinsTheElection.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckWhoWinsTheElection(A): 12 | counter = maxCounter = 0 13 | candidate = A[0] 14 | for i in range(0, len(A)): 15 | counter = 1 16 | for j in range(i + 1, len(A)): 17 | if(A[i] == A[j]): 18 | counter += 1 19 | if(counter > maxCounter): 20 | maxCounter = counter 21 | candidate = A[i] 22 | print candidate, "appeared ", maxCounter, " times" 23 | 24 | A = [3, 2, 1, 2, 2, 3] 25 | CheckWhoWinsTheElection(A) 26 | A = [3, 3, 3, 2, 2, 3] 27 | CheckWhoWinsTheElection(A) 28 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckWhoWinsTheElection.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckWhoWinsTheElection(A): 12 | counter = maxCounter = 0 13 | candidate = A[0] 14 | for i in range(0, len(A)): 15 | counter = 1 16 | for j in range(i + 1, len(A)): 17 | if(A[i] == A[j]): 18 | counter += 1 19 | if(counter > maxCounter): 20 | maxCounter = counter 21 | candidate = A[i] 22 | print candidate, "appeared ", maxCounter, " times" 23 | 24 | A = [3, 2, 1, 2, 2, 3] 25 | CheckWhoWinsTheElection(A) 26 | A = [3, 3, 3, 2, 2, 3] 27 | CheckWhoWinsTheElection(A) 28 | -------------------------------------------------------------------------------- /src/chapter04stacks/QueueWithStacks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | class Queue(object): 12 | def __init__(self): 13 | self.S1 = [] 14 | self.S2 = [] 15 | 16 | def enqueue(self, data): 17 | self.S1.append(data) 18 | 19 | def dequeue(self): 20 | if not self.S2: 21 | while self.S1: 22 | self.S2.append(self.S1.pop()) 23 | return self.S2.pop() 24 | 25 | q = Queue() 26 | for i in xrange(5): 27 | q.enqueue(i) 28 | for i in xrange(5): 29 | print q.dequeue() 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/chapter05queues/QueueWithStacks.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | class Queue(object): 12 | def __init__(self): 13 | self.S1 = [] 14 | self.S2 = [] 15 | 16 | def enqueue(self, data): 17 | self.S1.append(data) 18 | 19 | def dequeue(self): 20 | if not self.S2: 21 | while self.S1: 22 | self.S2.append(self.S1.pop()) 23 | return self.S2.pop() 24 | 25 | q = Queue() 26 | for i in xrange(5): 27 | q.enqueue(i) 28 | for i in xrange(5): 29 | print q.dequeue() 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/EditDistance.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def editDistance(A, B): 12 | m = len(A) + 1 13 | n = len(B) + 1 14 | 15 | table = {} 16 | for i in range(m): table[i, 0] = i 17 | for j in range(n): table[0, j] = j 18 | for i in range(1, m): 19 | for j in range(1, n): 20 | cost = 0 if A[i - 1] == B[j - 1] else 1 21 | table[i, j] = min(table[i, j - 1] + 1, table[i - 1, j] + 1, table[i - 1, j - 1] + cost) 22 | 23 | return table[i, j] 24 | 25 | print(editDistance("Helloworld", "HalloWorld")) 26 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MaxContigousSumBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxContigousSum(A): 12 | maxSum = 0 13 | n = len(A) 14 | for i in range(1, n): 15 | for j in range(i, n): 16 | currentSum = 0 17 | for k in range(i, j + 1): 18 | currentSum += A[k] 19 | if(currentSum > maxSum): 20 | maxSum = currentSum 21 | 22 | return maxSum; 23 | 24 | A = [-2, 3, -16, 100, -4, 5] 25 | print MaxContigousSum(A) 26 | A = [-2, 11, -4, 13, -5, 2 ] 27 | print MaxContigousSum(A) 28 | A = [-15, -23, -476, -3, -292] 29 | print MaxContigousSum(A) 30 | -------------------------------------------------------------------------------- /src/chapter11searching/FrequencyCounterWithoutExtraSpace.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def frequencyCounter(A): 12 | pos = 0 13 | n = len(A) 14 | while(pos < n): 15 | expectedPos = A[pos] - 1 16 | if(A[pos] > 0 and A[expectedPos] > 0): 17 | A[pos], A[expectedPos] = A[expectedPos], A[pos] 18 | A[expectedPos] = -1 19 | elif(A[pos] > 0): 20 | A[expectedPos] -= 1 21 | A[pos] = 0 22 | pos += 1 23 | else: 24 | pos += 1 25 | for i in range(1, n): 26 | print i + 1 , "--->", abs(A[i]) 27 | 28 | A = [10, 1, 9, 4, 7, 6, 5, 5, 1, 2, 1] 29 | frequencyCounter(A) 30 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/CountNumberofSetbitsin1toN.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | 13 | def counting_number_of_ones_in_1_to_N(n): 14 | count = 0 15 | for i in range(1, n+1): 16 | j = i; 17 | while(j): 18 | count += 1 19 | j &= j - 1 20 | print count 21 | 22 | n = 2 23 | counting_number_of_ones_in_1_to_N(n) 24 | n = 5 25 | counting_number_of_ones_in_1_to_N(n) 26 | n = 7 27 | counting_number_of_ones_in_1_to_N(n) 28 | n = 8 29 | counting_number_of_ones_in_1_to_N(n) 30 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/ReorderList.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def oddeven(A): 12 | "Odd-Even sort implementation" 13 | sorted = False 14 | while(not sorted): 15 | sorted = True 16 | for i in range(1, len(A) - 1, 2): 17 | if A[i] > A[i + 1]: 18 | A[i], A[i + 1] = A[i + 1], A[i] 19 | sorted = False 20 | for i in range(0, len(A) - 1, 2): 21 | if A[i] > A[i + 1]: 22 | A[i], A[i + 1] = A[i + 1], A[i] 23 | sorted = False 24 | if not sorted: 25 | print A 26 | -------------------------------------------------------------------------------- /src/chapter09graphs/DetectCycleInGraph.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def DetectCycle(G) : 12 | for i in range(0, G.numVertices): 13 | Visited[s] = 0 14 | Predecessor[i] = 0 15 | 16 | for i in range(0, G.numVertices): 17 | if(not Visited[i] and HasCycle(G, i)): 18 | return 1 19 | return False 20 | 21 | def HasCycle(G, u) : 22 | Visited[u] = 1 23 | for i in range(0, G.numVertices): 24 | if(G.adjMatrix[s][i]) : 25 | if(Predecessor[i] != u and Visited[i]): 26 | return 1 27 | else: 28 | Predecessor[i] = u 29 | return HasCycle(G, i) 30 | return 0 31 | 32 | -------------------------------------------------------------------------------- /src/chapter11searching/MaxRepititionsWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxRepititionsWithHash(A): 12 | table = {} # hash 13 | max = 0 14 | for element in A: 15 | if element in table: 16 | table[element] += 1 17 | elif element != " ": 18 | table[element] = 1 19 | else: 20 | table[element] = 0 21 | 22 | for element in A: 23 | if table[element] > max: 24 | max = table[element] 25 | maxRepeatedElement = element 26 | 27 | print maxRepeatedElement, "repeated for ", max, " times" 28 | 29 | A = [3, 2, 1, 3, 2, 3, 2, 3, 3] 30 | MaxRepititionsWithHash(A) 31 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/ClosestPairBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | from math import sqrt, pow 12 | 13 | def distance(a, b): 14 | return sqrt(pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2)) 15 | 16 | def bruteMin(points, current=float("inf")): 17 | if len(points) < 2: return current 18 | else: 19 | head = points[0] 20 | del points[0] 21 | newMin = min([distance(head, x) for x in points]) 22 | newCurrent = min([newMin, current]) 23 | return bruteMin(points, newCurrent) 24 | 25 | A = [(12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] 26 | print bruteMin(A) 27 | -------------------------------------------------------------------------------- /src/chapter01introduction/NLogNwithLoops.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | count = 0 14 | if n <= 0: 15 | return 16 | for i in range(1, n): 17 | j = 1 18 | while j < n: 19 | j = j + i 20 | count = count + 1 21 | print (count) 22 | 23 | function(20) 24 | 25 | def Function2(n): 26 | for i in range(1, n): 27 | j = 1 28 | while j <= n: 29 | j = j * 2 30 | print("*") 31 | 32 | Function2(20) 33 | 34 | import math 35 | def function(n): 36 | for i in range(1, n / 3): 37 | j = 1 38 | while j <= n: 39 | j = j + 4 40 | print("*") 41 | 42 | function(20) 43 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/OrderedInsertLinkedList.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def orderedInsert(self, item): 12 | current = self.head 13 | previous = None 14 | stop = False 15 | while current != None and not stop: 16 | if current.get_data() > item: 17 | stop = True 18 | else: 19 | previous = current 20 | current = current.get_next() 21 | 22 | temp = Node(item) 23 | if previous == None: 24 | temp.set_next(self.head) 25 | self.head = temp 26 | else: 27 | temp.set_next(current) 28 | previous.set_next(temp) 29 | -------------------------------------------------------------------------------- /src/chapter06trees/CountBSTs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CountTrees(n) : 12 | if (n <= 1): 13 | return 1 14 | else : 15 | # there will be one value at the root, with whatever remains on the left and right 16 | # each forming their own subtrees. Iterate through all the values that could be the root... 17 | sum = 0 18 | for root in range(1, n + 1): 19 | left = CountTrees(root - 1) 20 | right = CountTrees(n - root) 21 | # number of possible trees with this root == left*right 22 | sum += left * right 23 | 24 | return(sum) 25 | for i in range(1, 11): 26 | print CountTrees(i) 27 | -------------------------------------------------------------------------------- /src/chapter06trees/TreemaxDepth.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def maxDepth(root): 12 | if root == None: 13 | return 0 14 | return max(maxDepth(root.getLeft()), maxDepth(root.getRight())) + 1 15 | 16 | def maxDepth(self, root): 17 | if root == None: 18 | return 0 19 | q = [] 20 | q.append([root, 1]) 21 | temp = 0 22 | while len(q) != 0: 23 | node, depth = q.pop() 24 | depth = max(temp, dep) 25 | if node.getLeft() != None: 26 | q.append([node.getLeft(), depth + 1]) 27 | if node.getRight() != None: 28 | q.append([node.getRight(), depth + 1]) 29 | return temp 30 | 31 | -------------------------------------------------------------------------------- /src/chapter09graphs/CutVertices.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import math 12 | adjMatrix = [[0 for x in G.numVertices] for x in G.numVertices] 13 | dfsnum = [0] * G.numVertices 14 | num = 0 15 | low = [0] * G.numVertices 16 | def CutVertices(G, u) : 17 | low[u] = num 18 | dfsnum[u] = num 19 | num = num + 1 20 | for v in range(0, G.numVertices): 21 | if(G.adjMatrix[u][v] and dfsnum[v] == -1): 22 | CutVertices(v) 23 | if(low[v] > dfsnum[u]): 24 | print "Cut Vetex:", u 25 | low[u] = min (low[u] , low[v]) 26 | 27 | else: # (u,v) is a back edge 28 | low[u ] = min(low[u] , dfsnum[v]) 29 | -------------------------------------------------------------------------------- /src/chapter04stacks/RemoveAdjacentDuplicates.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def removeAdjacentDuplicates(str): 12 | stkptr = -1 13 | i = 0 14 | size = len(str) 15 | while i < size: 16 | if (stkptr == -1 or str[stkptr] != str[i]): 17 | stkptr += 1 18 | str[stkptr] = str[i] 19 | i += 1 20 | else: 21 | while i < size and str[stkptr] == str[i]: 22 | i += 1 23 | stkptr -= 1 24 | stkptr += 1 25 | str = str[0:stkptr] 26 | print str 27 | removeAdjacentDuplicates(['6', '2', '4', '1', '2', '1', '2', '2', '1']) 28 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/ShuffleArrayWithDivideAndConquer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def shuffleArray(A, l, r): 12 | # Array center 13 | c = l + (r - l) / 2 14 | q = 1 + l + (c - l) / 2 15 | if(l == r): # Base case when the array has only one element 16 | return 17 | k = 1 18 | I = q 19 | while(i <= c): 20 | # Swap elements around the center 21 | tmp = A[i] 22 | A[i] = A[c + k] 23 | A[c + k] = tmp 24 | i += 1 25 | k += 1 26 | 27 | ShuffleArray(A, l, c) # Recursively call the function on the left and right 28 | ShuffleArray(A, c + 1, r) # Recursively call the function on the right 29 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MaxContigousSumWithoutDPEfficient.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxContigousSum(A): 12 | sumSoFar = sumEndingHere = 0 13 | n = len(A) 14 | for i in range(0, n) : 15 | sumEndingHere = sumEndingHere + A[i] 16 | if(sumEndingHere < 0): 17 | sumEndingHere = 0 18 | continue 19 | if(sumSoFar < sumEndingHere): 20 | sumSoFar = sumEndingHere 21 | 22 | return sumSoFar 23 | 24 | 25 | A = [-2, 3, -16, 100, -4, 5] 26 | print MaxContigousSum(A) 27 | A = [-2, 11, -4, 13, -5, 2 ] 28 | print MaxContigousSum(A) 29 | A = [-15, -23, -476, -3, -292] 30 | print MaxContigousSum(A) 31 | -------------------------------------------------------------------------------- /src/chapter09graphs/BridgesInGraphs.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import math 12 | adjMatrix = [[0 for x in G.numVertices] for x in G.numVertices] 13 | dfsnum = [0] * G.numVertices 14 | num = 0 15 | low = [0] * G.numVertices 16 | def Bridges(G, u) : 17 | low[u] = num 18 | dfsnum[u] = num 19 | num = num + 1 20 | for v in range(0, G.numVertices): 21 | if(G.adjMatrix[u][v] and dfsnum[v] == -1): 22 | cutVertices(v) 23 | if(low[v] > dfsnum[u]): 24 | print (u, v) # as a bridge 25 | low[u] = min (low[u] , low[v]) 26 | else: # (u,v) is a back edge 27 | low[u ] = min(low[u] , dfsnum[v]) 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/01KnapSackWithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def Knapsack(knapsackSize, itemsValue, itemsWeight): 12 | numItems = len(itemsValue) 13 | M = [[0 for x in range(knapsackSize + 1)] for x in range(len(itemsValue))] 14 | for i in range(1, numItems): 15 | for j in range(knapsackSize + 1): 16 | value = itemsValue[i] 17 | weight = itemsWeight[i] 18 | if weight > j: 19 | M[i][j] = M[i - 1][j] 20 | else: 21 | M[i][j] = max(M[i - 1][j], M[i - 1][j - weight] + value) 22 | 23 | return M[numItems - 1][knapsackSize] 24 | 25 | print Knapsack(50, [60, 100, 120], [10, 20, 30]) 26 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/RemoveAdjacentDuplicates.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def removeAdjacentDuplicates(str): 12 | stkptr = -1 13 | i = 0 14 | size = len(str) 15 | while i < size: 16 | if (stkptr == -1 or str[stkptr] != str[i]): 17 | stkptr += 1 18 | str[stkptr] = str[i] 19 | i += 1 20 | else: 21 | while i < size and str[stkptr] == str[i]: 22 | i += 1 23 | stkptr -= 1 24 | stkptr += 1 25 | str = str[0:stkptr] 26 | print str 27 | removeAdjacentDuplicates(['6', '2', '4', '1', '2', '1', '2', '2', '1']) 28 | -------------------------------------------------------------------------------- /src/chapter10sorting/CheckWhoWinsTheElectionWithOutSpace.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckWhoWinsTheElection(A): 12 | A.sort() 13 | counter = maxCounter = 0 14 | candidate = maxCandidate = 0 15 | 16 | for i in range(0, len(A)): 17 | if(A[i] == candidate): 18 | counter += 1 19 | else: 20 | counter = 1 21 | candidate = A[i] 22 | 23 | if(counter > maxCounter): 24 | maxCandidate = A[i] 25 | maxCounter = counter 26 | 27 | print maxCandidate, "appeared ", maxCounter, " times" 28 | 29 | 30 | A = [2, 3, 2, 1, 2, 2, 3, 2, 2] 31 | CheckWhoWinsTheElection(A) 32 | A = [3, 3, 3, 2, 2, 3] 33 | CheckWhoWinsTheElection(A) 34 | -------------------------------------------------------------------------------- /src/chapter11searching/CheckWhoWinsTheElectionWithOutSpace.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def CheckWhoWinsTheElection(A): 12 | A.sort() 13 | counter = maxCounter = 0 14 | candidate = maxCandidate = 0 15 | 16 | for i in range(0, len(A)): 17 | if(A[i] == candidate): 18 | counter += 1 19 | else: 20 | counter = 1 21 | candidate = A[i] 22 | 23 | if(counter > maxCounter): 24 | maxCandidate = A[i] 25 | maxCounter = counter 26 | 27 | print maxCandidate, "appeared ", maxCounter, " times" 28 | 29 | 30 | A = [2, 3, 2, 1, 2, 2, 3, 2, 2] 31 | CheckWhoWinsTheElection(A) 32 | A = [3, 3, 3, 2, 2, 3] 33 | CheckWhoWinsTheElection(A) 34 | -------------------------------------------------------------------------------- /src/chapter11searching/FindInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findInRotatedSortedArray(A, target): 12 | left = 0 13 | right = len(A) - 1 14 | while left <= right: 15 | mid = (left + right) / 2 16 | if A[mid] == target: 17 | return mid 18 | if A[mid] >= A[left]: 19 | if A[left] <= target < A[mid]: 20 | right = mid - 1 21 | else: 22 | left = mid + 1 23 | else: 24 | if A[mid] < target <= A[right]: 25 | left = mid + 1 26 | else: 27 | right = mid - 1 28 | return -1 29 | 30 | A = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] 31 | 32 | print findInRotatedSortedArray(A, 5) 33 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/ReverseWordsInSentence.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | # @param s, a string 12 | # @return a string 13 | def reverseWordsInSentence(self, s): 14 | result = [] 15 | inWord = False 16 | for i in range(0, len(s)): 17 | if (s[i] == ' ' or s[i] == '\t') and inWord: 18 | inWord = False 19 | result.insert(0, s[start:i]) 20 | result.insert(0, ' ') 21 | elif not (s[i] == ' ' or s[i] == '\t' or inWord): 22 | inWord = True 23 | start = i 24 | if inWord: 25 | result.insert(0, s[start:len(s)]) 26 | result.insert(0, ' ') 27 | if len(result) > 0: 28 | result.pop(0) 29 | return ''.join(result) 30 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MaxContigousSumWithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def MaxContigousSum(A): 12 | maxSum = 0 13 | n = len(A) 14 | M = [0] * (n + 1) 15 | if(A[0] > 0): 16 | M[0] = A[0] 17 | else: M[0] = 0 18 | for i in range(1, n): 19 | if(M[i - 1] + A[i] > 0): 20 | M[i] = M[i - 1] + A[i] 21 | else: M[i] = 0 22 | 23 | for i in range(0, n): 24 | if(M[i] > maxSum): 25 | maxSum = M[i] 26 | 27 | return maxSum 28 | 29 | A = [-2, 3, -16, 100, -4, 5] 30 | print MaxContigousSum(A) 31 | A = [-2, 11, -4, 13, -5, 2 ] 32 | print MaxContigousSum(A) 33 | A = [-15, -23, -476, -3, -292] 34 | print MaxContigousSum(A) 35 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MinJumpsDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import sys 12 | def minJumps(A): 13 | n = len(A) 14 | jumps = [0] * (n) 15 | if (n == 0 or A[0] == 0): 16 | return sys.maxint + 1 17 | 18 | jumps[0] = 0 19 | for i in range(1, n): 20 | jumps[i] = sys.maxint + 1 21 | for j in range(0, i): 22 | if (i <= j + A[j] and jumps[j] != sys.maxint + 1): 23 | jumps[i] = min(jumps[i], jumps[j] + 1) 24 | break 25 | return jumps[n - 1] 26 | 27 | A = [1, 3, 6, 1, 0, 9] 28 | print "Minimum number of jumps to reach end is ", minJumps(A) 29 | 30 | A = [2, 3, 1, 1, 4] 31 | print "Minimum number of jumps to reach end is ", minJumps(A) 32 | -------------------------------------------------------------------------------- /src/chapter01introduction/RecursiveComplexityFNby3.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def function(n): 13 | if n <= 0: 14 | return 15 | for i in range(1, 3): # This loop executes 3 times with recursive value of n/3 value 16 | function(n / 3) 17 | function(20) 18 | 19 | def Function2(n): 20 | if n <= 0: 21 | return 22 | for i in range(1, 3): # This loop executes 3 times with recursive value of n/3 value 23 | Function2(n - 1) 24 | Function2(20) 25 | 26 | def Function3(n): 27 | if n <= 0: 28 | return 29 | for i in range(1, 3): # This loop executes 3 times with recursive value of n/3 value 30 | Function3(0.8 * n) 31 | Function3(20) 32 | 33 | -------------------------------------------------------------------------------- /src/chapter11searching/TwoElementsClosestToZeroBruteForce.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def TwoElementsClosestToZero(A): 12 | n = len(A) 13 | if(n < 2): 14 | print "Invalid Input" 15 | return 16 | minLeft = 0 17 | minRight = 1 18 | minSum = A[0] + A[1] 19 | for l in range(1, n - 1): 20 | for r in range(l + 1, n): 21 | sum = A[l] + A[r]; 22 | if(abs(minSum) > abs(sum)): 23 | minSum = sum 24 | minLeft = l 25 | minRight = r 26 | print " The two elements whose sum is minimum are ", A[minLeft], A[minRight] 27 | 28 | A = [1, 60, -10, 70, -80, 85] 29 | TwoElementsClosestToZero(A) 30 | A = [10, 8, 3, 5, -9, -7, 6] 31 | TwoElementsClosestToZero(A) 32 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MaxSumWithNoTwoContinuousNumbers.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def maxSumWithNoTwoContinuousNumbers(A): 12 | n = len(A) 13 | M = [0] * (n + 1) 14 | M[0] = A[0] 15 | 16 | if(A[0] > A[1]): 17 | M[0] = A[0] 18 | else: M[0] = A[1] 19 | for i in range(2, n): 20 | if(M[i - 1] > M[i - 2] + A[i]): 21 | M[i] = M[i - 1] 22 | else: M[i] = M[i - 2] + A[i] 23 | 24 | return M[n - 1] 25 | 26 | A = [-2, 3, -16, 100, -4, 5] 27 | print maxSumWithNoTwoContinuousNumbers(A) 28 | A = [-2, 11, -4, 13, -5, 2 ] 29 | print maxSumWithNoTwoContinuousNumbers(A) 30 | A = [-15, -23, -476, -3, -292] 31 | print maxSumWithNoTwoContinuousNumbers(A) 32 | -------------------------------------------------------------------------------- /src/chapter11searching/ThreeElementsWithSumKWithSorting.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def threeElementsWithSumKWithSorting(A, K): 12 | n = len(A) 13 | left = 0 14 | right = n - 1 15 | for i in range(0, n - 2): 16 | left = i + 1 17 | right = n - 1 18 | while(left < right): 19 | print A[i] + A[left] + A[right], K 20 | if(A[i] + A[left] + A[right] == K): 21 | print "yes-->", A[i], " + ", A[left], " + ", A[right], " = ", K 22 | return 1 23 | elif(A[i] + A[left] + A[right] < K): 24 | left += 1 25 | else: 26 | right -= 1 27 | return 0 28 | 29 | A = [1, 6, 45, 4, 10, 18] 30 | A.sort() 31 | print threeElementsWithSumKWithSorting(A, 23) 32 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/LargestRectangleArea.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def largestRectangleArea(self, height): 12 | stack = []; i = 0; maxArea = 0 13 | while i < len(height): 14 | if stack == [] or height[i] > height[stack[len(stack) - 1]]: 15 | stack.append(i) 16 | else: 17 | curr = stack.pop() 18 | width = i if stack == [] else i - stack[len(stack) - 1] - 1 19 | maxArea = max(maxArea, width * height[curr]) 20 | i -= 1 21 | i += 1 22 | while stack != []: 23 | curr = stack.pop() 24 | width = i if stack == [] else len(height) - stack[len(stack) - 1] - 1 25 | maxArea = max(maxArea, width * height[curr]) 26 | return maxArea 27 | -------------------------------------------------------------------------------- /src/chapter10sorting/QuickSort2.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def quickSort(A,low,high): 12 | if low >= high: 13 | return 14 | pivot = A[low] 15 | i = low+1 16 | j = high 17 | while i <= j: 18 | while i <= j and A[i] <= pivot: 19 | i = i + 1 20 | while A[j] >= pivot and j >= i: 21 | j = j -1 22 | if j < i: 23 | break 24 | A[i], A[j] = A[j], A[i] 25 | 26 | A[low], A[j] = A[j], A[low] 27 | partitionPoint = j 28 | 29 | quickSort(A,low,partitionPoint-1) 30 | quickSort(A,partitionPoint+1,high) 31 | 32 | A = [5, 1, 32, 54, 12, 6, 32, 2, 5, 19, 99, 9] 33 | quickSort(A,0,len(A)-1) 34 | print(A) 35 | -------------------------------------------------------------------------------- /src/chapter11searching/MaxIndexDifferenceEfficient.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def maxIndexDiff(A): 12 | n = len(A) 13 | LeftMins = [0] * (n) 14 | RightMaxs = [0] * (n) 15 | LeftMins[0] = A[0] 16 | for i in range(1, n): 17 | LeftMins[i] = min(A[i], LeftMins[i - 1]) 18 | 19 | RightMaxs[n - 1] = A[n - 1] 20 | for j in range(n - 2, -1, -1): 21 | RightMaxs[j] = max(A[j], RightMaxs[j + 1]) 22 | 23 | i = 0; j = 0; maxDiff = -1; 24 | while (j < n and i < n): 25 | if (LeftMins[i] < RightMaxs[j]): 26 | maxDiff = max(maxDiff, j - i) 27 | j = j + 1 28 | else: 29 | i = i + 1 30 | return maxDiff 31 | 32 | A = [34, 8, 10, 3, 2, 80, 30, 33, 1] 33 | print maxIndexDiff(A) 34 | -------------------------------------------------------------------------------- /src/chapter10sorting/RadixSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def RadixSort(A): 12 | RADIX = 10 13 | maxLength = False 14 | tmp , placement = -1, 1 15 | 16 | while not maxLength: 17 | maxLength = True 18 | buckets = [list() for _ in range(RADIX)] 19 | for i in A: 20 | tmp = i / placement 21 | buckets[tmp % RADIX].append(i) 22 | if maxLength and tmp > 0: 23 | maxLength = False 24 | 25 | a = 0 26 | for b in range(RADIX): 27 | buck = buckets[b] 28 | for i in buck: 29 | A[a] = i 30 | a += 1 31 | 32 | # move to next digit 33 | placement *= RADIX 34 | 35 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 36 | print(RadixSort(A)) 37 | -------------------------------------------------------------------------------- /src/chapter11searching/BinarySearcLastOccurrence.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def binarySearchLastOccurrence(A, target): 12 | if A == None or len(A) == 0: 13 | return -1; 14 | high = len(A) - 1 15 | low = 0 16 | m = 0 17 | lastFound = -1; 18 | while(1): 19 | if (low > high): return lastFound 20 | m = (low + high) / 2 21 | if (A[m] == target): 22 | lastFound = m; low = m + 1 23 | if (A[m] < target): low = m + 1 24 | if (A[m] > target): high = m - 1 25 | 26 | return m 27 | 28 | A = [5, 6, 9, 12, 15, 21, 21, 34, 45, 57, 70, 84] 29 | print binarySearchLastOccurrence(A, 21) 30 | -------------------------------------------------------------------------------- /src/chapter11searching/BinarySearchFirstOccurrence.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def binarySearchFirstOccurrence(A, target): 12 | if A == None or len(A) == 0: 13 | return -1; 14 | high = len(A) - 1 15 | low = 0 16 | m = 0 17 | lastFound = -1; 18 | while(1): 19 | if (low > high): return lastFound 20 | m = (low + high) / 2 21 | if (A[m] == target): 22 | lastFound = m; high = m - 1 23 | if (A[m] < target): low = m + 1 24 | if (A[m] > target): high = m - 1 25 | 26 | return m 27 | 28 | A = [5, 6, 9, 12, 15, 21, 21, 34, 45, 57, 70, 84] 29 | print binarySearchFirstOccurrence(A, 21) 30 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/ExponentialWithDivideAndConquer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import math 12 | def power_brute_force(k, n): 13 | """linear power algorithm""" 14 | x = k 15 | for i in range(1, n): 16 | x *= k 17 | return x 18 | 19 | print power_brute_force(2, 3) 20 | 21 | 22 | 23 | def power_divide_and_conquer(k, n): 24 | """Divide and Conquer power algorithm""" 25 | 26 | # base case 27 | if n == 0: 28 | return 1 29 | 30 | # base case 31 | if k == 0: 32 | return 0 33 | 34 | x = power_divide_and_conquer(a, math.floor(n/2)) 35 | if n % 2 == 0: 36 | return x * x 37 | else: 38 | return k * x * x 39 | 40 | print power_divide_and_conquer(2, 4) 41 | 42 | -------------------------------------------------------------------------------- /src/chapter11searching/MoveZerosToEnd.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def moveZerosToEnd(A): 12 | i = j = 0 13 | while (i <= len(A) - 1): 14 | if (A[i] != 0): 15 | A[j] = A[i] 16 | j += 1 17 | i += 1 18 | while (j <= len(A) - 1): 19 | A[j] = 0 20 | j += 1 21 | return A 22 | A = [7, 0, 0, 3, 0, 2, 3, 3, 6, 3] 23 | print A, "\n", moveZerosToEnd(A) 24 | 25 | def mySwap(A, i, j): 26 | temp = A[i] 27 | A[i] = A[j] 28 | A[j] = temp 29 | 30 | def moveZerosToEnd2(A): 31 | i = j = 0 32 | while (i <= len(A) - 1): 33 | if (A[i] != 0): 34 | mySwap(A, j, i) 35 | j += 1 36 | i += 1 37 | return A 38 | 39 | A = [7, 0, 0, 3, 0, 2, 3, 3, 6, 3] 40 | print A, "\n", moveZerosToEnd2(A) 41 | -------------------------------------------------------------------------------- /src/chapter11searching/BinarySearchRecursive.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchRecursive(numbersList, value, low=0, high=-1): 12 | if not numbersList: return -1 13 | if(high == -1): high = len(numbersList) - 1 14 | if low == high: 15 | if numbersList[low] == value: return low 16 | else: return -1 17 | mid = low + (high - low) // 2 18 | if numbersList[mid] > value: return BinarySearchRecursive(numbersList, value, low, mid - 1) 19 | elif numbersList[mid] < value: return BinarySearchRecursive(numbersList, value, mid + 1, high) 20 | else: return mid 21 | 22 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 23 | print(BinarySearchRecursive(A, 277)) 24 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/NumberPlusone.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | #!/usr/bin/env python 12 | ''' 13 | Given a number represented as an array of digits, plus one to the number. 14 | ''' 15 | from __future__ import division 16 | import random 17 | 18 | def plus_one(digits): 19 | print digits, '+ 1 =', 20 | carry = 1 21 | for i in reversed(xrange(len(digits))): 22 | x = digits[i] 23 | carry, x = divmod(x + carry, 10) 24 | digits[i] = x 25 | if carry > 0: digits.insert(0, carry) 26 | print digits 27 | return digits 28 | 29 | if __name__ == '__main__': 30 | plus_one([1, 2, 3, 4]) 31 | plus_one([1, 9, 9]) 32 | plus_one([9, 9, 9]) 33 | plus_one([0]) 34 | -------------------------------------------------------------------------------- /src/chapter10sorting/FinSUMInTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchIterative(numbersList, value): 12 | low = 0 13 | high = len(numbersList) - 1 14 | while low <= high: 15 | mid = (low + high) // 2 16 | if numbersList[mid] > value: high = mid - 1 17 | elif numbersList[mid] < value: low = mid + 1 18 | else: return mid 19 | return -1 20 | 21 | def findSumInLists(A, B, k): 22 | A.sort() 23 | for i in range(0, len(B)): 24 | c = k - B[i] 25 | if(BinarySearchIterative(A, c) != -1): 26 | return 1 27 | return 0 28 | 29 | 30 | A = [2, 3, 5, 7, 12, 15, 23, 32, 42] 31 | B = [3, 13, 13, 15, 22, 33] 32 | print findSumInLists(A, B, 270) 33 | -------------------------------------------------------------------------------- /src/chapter11searching/FinSUMInTwoSortedArrays.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchIterative(numbersList, value): 12 | low = 0 13 | high = len(numbersList) - 1 14 | while low <= high: 15 | mid = (low + high) // 2 16 | if numbersList[mid] > value: high = mid - 1 17 | elif numbersList[mid] < value: low = mid + 1 18 | else: return mid 19 | return -1 20 | 21 | def findSumInLists(A, B, k): 22 | A.sort() 23 | for i in range(0, len(B)): 24 | c = k - B[i] 25 | if(BinarySearchIterative(A, c) != -1): 26 | return 1 27 | return 0 28 | 29 | 30 | A = [2, 3, 5, 7, 12, 15, 23, 32, 42] 31 | B = [3, 13, 13, 15, 22, 33] 32 | print findSumInLists(A, B, 270) 33 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/BinarySearchRecursive.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def BinarySearchRecursive(numbersList, value, low=0, high=-1): 12 | if not numbersList: return -1 13 | if(high == -1): high = len(numbersList) - 1 14 | if low == high: 15 | if numbersList[low] == value: return low 16 | else: return -1 17 | mid = low + (high - low) // 2 18 | if numbersList[mid] > value: return BinarySearchRecursive(numbersList, value, low, mid - 1) 19 | elif numbersList[mid] < value: return BinarySearchRecursive(numbersList, value, mid + 1, high) 20 | else: return mid 21 | 22 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 23 | print(BinarySearchRecursive(A, 277)) 24 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/MakingChangeWithDP.py: -------------------------------------------------------------------------------- 1 | def MakingChange(coins, change, minimumCoins, coinsUsed): 2 | for cents in range(change + 1): 3 | coinCount = cents 4 | newCoin = 1 5 | for j in [c for c in coins if c <= cents]: 6 | if minimumCoins[cents - j] + 1 < coinCount: 7 | coinCount = minimumCoins[cents - j] + 1 8 | newCoin = j 9 | minimumCoins[cents] = coinCount 10 | coinsUsed[cents] = newCoin 11 | return minimumCoins[change] 12 | 13 | def printingCoins(coinsUsed, change): 14 | coin = change 15 | while coin > 0: 16 | thisCoin = coinsUsed[coin] 17 | print(thisCoin) 18 | coin = coin - thisCoin 19 | 20 | def main(): 21 | amountToGetChange = 63 22 | coins = [1, 5, 10, 21, 25] 23 | coinsUsed = [0] * (amountToGetChange + 1) 24 | coinCount = [0] * (amountToGetChange + 1) 25 | 26 | print("Making change for", amountToGetChange, "requires") 27 | print(MakingChange(coins, amountToGetChange, coinCount, coinsUsed), "coins") 28 | print("They are:") 29 | printingCoins(coinsUsed, amountToGetChange) 30 | print("The used list is as follows:") 31 | print(coinsUsed) 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /src/chapter06trees/AreStructurullySameTrees.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def areStructurullySameTrees(root1, root2): 12 | if (not root1.left) and not (root1.right) and (not root2.left) and \ 13 | not (root2.right) and root1.data == root2.data: 14 | return True 15 | 16 | if (root1.data != root2.data) or (root1.left and not root2.left) or \ 17 | (not root1.left and root2.left) or (root1.right and not root2.right) \ 18 | or (not root1.right and root2.right): 19 | return False 20 | 21 | left = areStructurullySameTrees(root1.left, root2.left) if root1.left and root2.left else True 22 | right = areStructurullySameTrees(root1.right, root2.right) if root1.right and root2.right else True 23 | return left and right 24 | -------------------------------------------------------------------------------- /src/chapter11searching/FindMinimumInRotatedSortedArray.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def findMinimumInRotatedSortedArray(A): 12 | mid, low, high = 0, 0, len(A) - 1 13 | while A[low] >= A[high]: 14 | if high - low <= 1: 15 | return A[high], high 16 | mid = (low + high) >> 1 17 | if A[mid] == A[low]: 18 | low += 1 19 | elif A[mid] > A[low]: 20 | low = mid 21 | elif A[mid] == A[high]: 22 | high -= 1 23 | else: 24 | high = mid 25 | return A[low], low 26 | 27 | A = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] 28 | print findMinimumInRotatedSortedArray(A) 29 | -------------------------------------------------------------------------------- /src/chapter15stringalgorithms/Combinations.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def combinationByRecursion(elems, s, idx, li): 12 | for i in range(idx, len(elems)): 13 | s += elems[i] 14 | li.append(s) 15 | # print s, idx 16 | combinationByRecursion(elems, s, i + 1, li) 17 | s = s[0:-1] 18 | 19 | def combinationByIteration(elems): 20 | level = [''] 21 | for i in range(len(elems)): 22 | nList = [] 23 | for item in level: 24 | nList.append(item + elems[i]) 25 | level += nList 26 | return level[1:] 27 | 28 | res = [] 29 | combinationByRecursion('abc', '', 0, res) 30 | print combinationByIteration('abc') 31 | print combinationByIteration('abc') 32 | -------------------------------------------------------------------------------- /src/chapter02recursionandbacktracking/BitSequences.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | 12 | def append_at_front(x, L): 13 | return [x + element for element in L] 14 | 15 | def bit_strings(n): 16 | if n == 0: return [] 17 | if n == 1: return ["0", "1"] 18 | else: 19 | return (append_at_front("0", bit_strings(n - 1)) + append_at_front("1", bit_strings(n - 1))) 20 | 21 | print bit_strings(4) 22 | 23 | def bit_strings2(n): 24 | if n == 0: return [] 25 | if n == 1: return ["0", "1"] 26 | return [ digit + bitstring for digit in bit_strings2(1) 27 | for bitstring in bit_strings2(n - 1)] 28 | print bit_strings2(4) 29 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/NthNodeFromEnd.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def nthNodeFromEnd(self, n): 12 | if 0 > n: 13 | return None 14 | 15 | # count k units from the self.head. 16 | temp = self.head 17 | count = 0 18 | while count < n and None != temp: 19 | temp = temp.next 20 | count += 1 21 | 22 | # if the LinkedList does not contain k elements, return None 23 | if count < n or None == temp: 24 | return None 25 | 26 | # keeping tab on the nth element from temp, slide temp until 27 | # temp equals self.tail. Then return the nth element. 28 | nth = self.head 29 | while None != temp.next: 30 | temp = temp.next 31 | nth = nth.next 32 | 33 | return nth 34 | -------------------------------------------------------------------------------- /src/chapter11searching/FindTwoRepeatingNumbersWithXOR.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | # Approach is same for two repeated and two missing numbers 12 | def findTwoRepeatingNumbersWithXOR (A): 13 | XOR = A[0] 14 | X = Y = 0 15 | n = len(A) - 2 16 | for i in range(1, len(A)): 17 | XOR ^= A[i] 18 | 19 | for i in range(1, n + 1): 20 | XOR ^= i 21 | rightMostSetBitNo = XOR & ~(XOR - 1) 22 | for i in range(0, len(A)): 23 | if(A[i] & rightMostSetBitNo): 24 | X = X ^ A[i] 25 | else: Y = Y ^ A[i] 26 | for i in range(1, n + 1): 27 | if(i & rightMostSetBitNo): 28 | X = X ^ i 29 | else: Y = Y ^ i 30 | print X, Y 31 | 32 | A = [4, 2, 4, 5, 2, 3, 1] 33 | findTwoRepeatingNumbersWithXOR(A) 34 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/LongestPalindromeSubsequence.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def LongestPalindromeSubsequence(A): 12 | n = len(A) 13 | L = [[0 for x in range(n)] for x in range(n)] 14 | # palindromes with length 1 15 | for i in range(0, n - 1): 16 | L[i][i] = 1 17 | 18 | # palindromes with length up to j+1 19 | for k in range(2, n + 1): 20 | for i in range(0, n - k + 1): 21 | j = i + k - 1 22 | if A[i] == A[j] and k == 2: 23 | L[i][j] = 2 24 | if A[i] == A[j]: 25 | L[i][j] = 2 + L[i + 1][j - 1] 26 | else: 27 | L[i][j] = max(L[i + 1][j] , L[i][j - 1]) 28 | 29 | # print L 30 | return L[0][n - 1] 31 | 32 | print LongestPalindromeSubsequence("Career Monk Publications") 33 | -------------------------------------------------------------------------------- /src/chapter11searching/TwoElementsClosestToZeroWithSorting.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import sys 12 | def TwoElementsClosestToZero(A): 13 | n = len(A) 14 | A.sort() 15 | if(n < 2): 16 | print "Invalid Input" 17 | return 18 | l = 0 19 | r = n - 1 20 | minLeft = l 21 | minRight = n - 1 22 | minSum = sys.maxint 23 | while(l < r): 24 | sum = A[l] + A[r]; 25 | if(abs(minSum) > abs(sum)): 26 | minSum = sum 27 | minLeft = l 28 | minRight = r 29 | if sum < 0: 30 | l += 1 31 | else: r -= 1 32 | print " The two elements whose sum is minimum are ", A[minLeft], A[minRight] 33 | 34 | A = [1, 60, -10, 70, -80, 85] 35 | TwoElementsClosestToZero(A) 36 | A = [10, 8, 3, 5, -9, -7, 6] 37 | TwoElementsClosestToZero(A) 38 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/StrategyOfCoinsGameWithDP.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | # row of n coins 12 | coins = [1, 2, 3, 4, 5] 13 | n = len(coins) 14 | 15 | # each time it is our turn, take the max of the two available moves (but the minimum of the opponent's two potential moves) 16 | V = [] 17 | for i in range(n): 18 | V.append([0] * n) 19 | 20 | for i in range(n): 21 | for j in range(n): 22 | if i == j: 23 | V[i][j] = coins[i] 24 | elif j == i + 1: 25 | V[i][j] = max(coins[i], coins[j]) 26 | 27 | # only valid if i < j 28 | if (i + 2) <= j: 29 | take_start = V[i + 2][j] 30 | else: 31 | take_start = 0 32 | if (i + 1) <= (j - 1): 33 | take_end = V[i + 1][j - 1] 34 | else: 35 | take_start = 0 36 | 37 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/Count_Apples_with_3ways_of_reaching.py: -------------------------------------------------------------------------------- 1 | def find_maximum_apples_count_3ways_of_reaching(Apples, n, m): 2 | S =[[0 for x in range(m)] for x in range(n)] 3 | 4 | # Initialize position S[0][0]. 5 | # We cannot collect any apples other than Apples[0][0] 6 | S[0][0] = Apples[0][0] 7 | 8 | # Initialize the first row 9 | for j in range(1, m): 10 | S[0][j] = Apples[0][j] + S[0][j-1] 11 | 12 | # Initialize the first column 13 | for i in range(1, n): 14 | S[i][0] = Apples[i][0] + S[i-1][0] 15 | 16 | for i in range(1, n): 17 | for j in range(1, m): 18 | previous_column = S[i][j-1] 19 | previous_row = S[i-1][j] 20 | previous_diagonal = S[i-1][j-1] 21 | 22 | if (previous_column >= previous_row) and (previous_column >= previous_diagonal): 23 | largest = previous_column 24 | elif (previous_row >= previous_column) and (previous_row >= previous_diagonal): 25 | largest = previous_row 26 | else: 27 | largest = previous_diagonal 28 | 29 | S[i][j] = Apples[i][j] + largest 30 | 31 | return S[n-1][m-1] 32 | 33 | Apples = [ [1, 2, 4, 7], [2, 1, 6, 1], [12, 5, 9, 19], [4, 29, 50, 60] ] 34 | print find_maximum_apples_count_3ways_of_reaching(Apples, len(Apples), len(Apples[0])) 35 | -------------------------------------------------------------------------------- /src/chapter19dynamicprogramming/RecusriveFunctionDPFromReccurence.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def f(n) : 12 | sum = 0 13 | if(n == 0 or n == 1): 14 | return 2 15 | # Recursive case 16 | for i in range(1, n): 17 | sum += 2 * f(i) * f(i - 1) 18 | return sum 19 | 20 | 21 | print f(4) 22 | 23 | 24 | 25 | def f2(n) : 26 | T = [0] * (n + 1) 27 | T[0] = T[1] = 2 28 | for i in range(2, n + 1): 29 | T[i] = 0 30 | for j in range(1, i): 31 | T[i] += 2 * T[j] * T[j - 1] 32 | 33 | return T[n] 34 | 35 | print f2(4) 36 | 37 | def f3(n): 38 | T = [0] * (n + 1) 39 | T[0] = T[1] = 2 40 | T[2] = 2 * T[0] * T[1] 41 | for i in range(3, n + 1): 42 | T[i] = T[i - 1] + 2 * T[i - 1] * T[i - 2] 43 | return T[n] 44 | 45 | 46 | print f3(4) 47 | -------------------------------------------------------------------------------- /src/chapter10sorting/QuickSort.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | import random 12 | def QuickSort(A, low, high): 13 | if low < high: 14 | pivot = Partition(A, low, high) 15 | QuickSort(A, low, pivot - 1) 16 | QuickSort(A, pivot + 1, high) 17 | 18 | def Partition(A, low, high) : 19 | pivot = low + random.randrange(high - low + 1) 20 | swap(A, pivot, high) 21 | for i in range(low, high): 22 | if A[i] <= A[high]: 23 | swap(A, i, low) 24 | low += 1 25 | 26 | swap(A, low, high) 27 | return low 28 | 29 | def swap(A, x, y): 30 | temp = A[x] 31 | A[x] = A[y] 32 | A[y] = temp 33 | 34 | A = [534, 246, 933, 127, 277, 321, 454, 565, 220] 35 | QuickSort(A, 0, len(A) - 1) 36 | print(A) 37 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/SprialIterativePrint.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def spiral_iterative(n): 12 | dx, dy = 1, 0 # Starting increments 13 | x, y = 0, 0 # Starting location 14 | matrix = [[None] * n for j in range(n)] 15 | for i in xrange(n ** 2): 16 | matrix[x][y] = i 17 | nx, ny = x + dx, y + dy 18 | if 0 <= nx < n and 0 <= ny < n and matrix[nx][ny] == None: 19 | x, y = nx, ny 20 | else: 21 | dx, dy = -dy, dx 22 | x, y = x + dx, y + dy 23 | return matrix 24 | 25 | def print_spiral(matrix): 26 | n = range(len(matrix)) 27 | for y in n: 28 | for x in n: 29 | print "%2i" % matrix[x][y], 30 | print 31 | 32 | print_spiral(spiral_iterative(5)) 33 | -------------------------------------------------------------------------------- /src/chapter11searching/FirstRepeatedElementAmongRepeatedElementsWithHash.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def FirstRepeatedElementAmongRepeatedElementsWithHash(A): 12 | table = {} # hash 13 | max = 0 14 | for element in A: 15 | if element in table and table[element] == 1: 16 | table[element] = -2 17 | elif element in table and table[element] < 0: 18 | table[element] -= 1 19 | elif element != " ": 20 | table[element] = 1 21 | else: 22 | table[element] = 0 23 | 24 | for element in A: 25 | if table[element] < max: 26 | max = table[element] 27 | maxRepeatedElement = element 28 | 29 | print maxRepeatedElement, "repeated for ", abs(max), " times" 30 | 31 | A = [3, 2, 1, 1, 2, 1, 2, 5, 5] 32 | FirstRepeatedElementAmongRepeatedElementsWithHash(A) 33 | -------------------------------------------------------------------------------- /src/chapter21miscconcepts/NumberOfOneBits.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def number_of_ones1(n): 12 | count = 0 13 | while(n): 14 | count += n & 1 15 | n >>= 1 16 | print count 17 | 18 | def number_of_ones2(n): 19 | count = 0 20 | while(n): 21 | if(n % 2 == 1): 22 | count += 1 23 | n = n / 2 24 | print count 25 | 26 | 27 | def number_of_ones3(n): 28 | count = 0 29 | while(n): 30 | count += 1 31 | n &= n - 1 32 | print count 33 | 34 | def number_of_ones4(n): 35 | Table = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4] 36 | count = 0 37 | while (n): 38 | count = count + Table[n & 0xF] 39 | n >>= 4 40 | print count 41 | 42 | 43 | 44 | n = 11 45 | number_of_ones1(n) 46 | number_of_ones2(n) 47 | number_of_ones3(n) 48 | number_of_ones4(n) 49 | -------------------------------------------------------------------------------- /src/chapter06trees/CheckPathWithSum.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def pathFinder(root, val, path, paths): 12 | if not root: 13 | return False 14 | 15 | if not root.left and not root.right: 16 | if root.data == val: 17 | path.append(root.data) 18 | paths.append(path) 19 | return True 20 | else: 21 | return False 22 | 23 | left = pathFinder(root.left, val - root.data, path + [root.data], paths) 24 | right = pathFinder(root.right, val - root.data, path + [root.data], paths) # make sure it can be executed! 25 | return left or right 26 | 27 | 28 | def hasPathWithSum(root, val): 29 | paths = [] 30 | pathFinder(root, val, [], paths) 31 | print 'sum:', val 32 | print 'paths:', paths 33 | -------------------------------------------------------------------------------- /src/chapter11searching/InterpolationSearch.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithmic Thinking With Python 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def InterpolationSearch(numbersList, value): 12 | low = 0 13 | high = len(numbersList) - 1 14 | while numbersList[low] <= value and numbersList[high] >= value: 15 | mid = (low + ((value - numbersList[low]) * (high - low)) 16 | / (numbersList[high] - numbersList[low])) 17 | if numbersList[mid] < value: 18 | low = mid + 1 19 | elif numbersList[mid] > value: 20 | high = mid - 1 21 | else: 22 | return mid 23 | if numbersList[low] == value: 24 | return low 25 | return None 26 | 27 | A = [-30,-16,-9,3,10,11,18,22,54,84,105] 28 | print InterpolationSearch(A, -9) 29 | -------------------------------------------------------------------------------- /src/chapter03linkedlists/GetIntersectionNode.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) Dec 22, 2014 CareerMonk Publications and others. 2 | # E-Mail : info@careermonk.com 3 | # Creation Date : 2014-01-10 06:15:46 4 | # Last modification : 2008-10-31 5 | # by : Narasimha Karumanchi 6 | # Book Title : Data Structures And Algorithms Made In Java 7 | # Warranty : This software is provided "as is" without any 8 | # warranty; without even the implied warranty of 9 | # merchantability or fitness for a particular purpose. 10 | 11 | def getIntersectionNode(self, list1, list2): 12 | currentList1, currentList2 = list1, list2 13 | list1Len, list2Len = 0, 0 14 | while currentList1 is not None: 15 | list1Len += 1 16 | currentList1 = currentList1.next 17 | while currentList2 is not None: 18 | list2Len += 1 19 | currentList2 = currentList2.next 20 | currentList1, currentList2 = list1, list2 21 | if list1Len > list2Len: 22 | for i in range(list1Len - list2Len): 23 | currentList1 = currentList1.next 24 | elif list2Len > list1Len: 25 | for i in range(list2Len - list1Len): 26 | currentList2 = currentList2.next 27 | while currentList2 != currentList1: 28 | currentList2 = currentList2.next 29 | currentList1 = currentList1.next 30 | return currentList1 31 | -------------------------------------------------------------------------------- /src/chapter18divideandconquer/find_peak-2d.py: -------------------------------------------------------------------------------- 1 | import random 2 | import pprint 3 | 4 | def peak_find_2d(matrix): 5 | j = len(matrix[0]) // 2 6 | 7 | # maxvalue is the global maximum in column j 8 | # rowmax is the row index of the maxvalue 9 | maxvalue, rowmax = -1, -1 10 | for row in range(len(matrix)): 11 | if maxvalue <= matrix[row][j]: 12 | maxvalue = matrix[row][j] 13 | rowmax = row 14 | 15 | left, right = 0, 0 16 | if j > 0: 17 | left = matrix[rowmax][j - 1] 18 | if j < len(matrix[0]) - 1: 19 | right = matrix[rowmax][j + 1] 20 | if left <= maxvalue >= right: 21 | return (rowmax, j, maxvalue) 22 | if left > maxvalue: 23 | half = [] 24 | for row in matrix: 25 | half.append(row[:j + 1]) 26 | return peak_find_2d(half) 27 | if right > maxvalue: 28 | half = [] 29 | for row in matrix: 30 | half.append(row[j:]) 31 | return peak_find_2d(half) 32 | 33 | def generate_2d_array(n=7, m=7, lower=0, upper=9): 34 | return [[random.randint(lower, upper) for _ in range(m)] for _ in range(n)] 35 | 36 | if __name__ == '__main__': 37 | matrix = generate_2d_array(upper=9) 38 | pprint.pprint(matrix) 39 | x = peak_find_2d(matrix) 40 | pprint.pprint(x) 41 | --------------------------------------------------------------------------------