├── #3_linkedLists.py ├── #4_Array.py ├── #5_Stacks_Queues.py ├── #6_Sorting.py ├── #7_Searching.py ├── A_To_The_Power_Of_P.py ├── Advanced_DLL.py ├── Binary Search Tree.py ├── Binary Search.py ├── BinarySearch_algorithm.py ├── CountTheDifference.py ├── CountingSort_Algorithm.py ├── CountingSort_Algorithm2.py ├── DLL_another.py ├── DP_flippingCoin.py ├── Double_LinkedList_implementation_from_book.py ├── Exp(RegularOne).py ├── FindFactors(Improved).py ├── FindFactors.py ├── FindPrimes.py ├── Finding Factors Fast.py ├── Finding Factors.py ├── GCD Algorithm.py ├── GCD(Great Common Divisor).py ├── Gnome_Sort.py ├── Huge_IsPrime_Miller_Rabin.py ├── Insertion_sorted_list.py ├── InterpolationSearch_algorithm.py ├── IsPrime.py ├── IsPrime_Miller_Rabin.py ├── LLStack_implementation_extra.py ├── LinearSearch_algorithm.py ├── LinkedList.py ├── LinkedList_Queue.py ├── LinkedList_Queue_extra.py ├── LinkedList_implementation_from_book.py ├── List_of_primes_faster.py ├── Matrices.py ├── MergeSort_Algorithm1.py ├── MergeSort_Algorithm2.py ├── MinHash.py ├── Number Theory ├── ChineseRemTheorem.py ├── CongruenceFinder.py ├── HornerPolyEval.py ├── IntegerSolutions.py ├── PPT_UnitCircle.py ├── README.md ├── Series.py ├── TrialDivision.py ├── eulerPhiFunction.py ├── extendedGCD.py ├── extendedGCD_print.py ├── gcd.py ├── incongruentFinder.py ├── largestPrime.py ├── lcm.py ├── lcmm.py └── pythagoreanTriples.py ├── One_Dimensional_lists.py ├── Pin Problem 1.py ├── Push_Pop_Array_stack.py ├── Push_Pop_Array_two_stack.py ├── Push_Pop_LLstack.py ├── QuickSort_algorithm.py ├── README.md ├── RandomizingArrays.py ├── Reverse_Array_Stack.py ├── RhoIntFactorization.py ├── Sample Challange.py ├── SelectionSort_algorithm.py ├── Stack_Selectionsort.py ├── Stack_insertionsort.py ├── Turn_array_into_heap.py ├── algorithmAnalysis.py ├── binaryConvertion.py ├── bubbleSort_algorithm.py ├── circular_array_queue.py ├── element_remover.py ├── example4.py ├── extra_stack_example.py ├── first_n_primes.py ├── hashMap.py ├── heap_sort.py ├── implementing_queue_using_lists.py ├── insertionSort_algorithm.py ├── longest sequence of repeated digits.py └── numInt.ipynb /#3_linkedLists.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eneskemalergin/Essential_Algorithms/bd59434b5d940c334694c623ed212e120ea171da/#3_linkedLists.py -------------------------------------------------------------------------------- /#4_Array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Chapter 4 # 3 | #-----------# 4 | import math 5 | # Question 1# 6 | #------------------------------------------------------------------------------# 7 | ''' 8 | Write an algorithm to calculate the sample variance of a one-dimensional 9 | array of numbers where the sample variance for an array containing 10 | N items is defined by this equation: 11 | 12 | S = 1/N (SumAll-from i=0 to N-1 with (xi - -x)^2) 13 | 14 | Here −x is the mean (average) of the values in the array, and the summation 15 | symbol Σ means to add up all the xi values as i varies from 0 to N – 1. 16 | ''' 17 | 18 | def findSampleVariance(list): 19 | # Finding the average 20 | total = 0 21 | for i in list: 22 | total += list[i] 23 | 24 | average = total / len(list) 25 | 26 | # Find the sample variance 27 | sum_of_squares = 0 28 | for j in list: 29 | sum_of_squares = sum_of_squares + (list[i] - average) * (list[i] - average) 30 | 31 | return sum_of_squares / len(list) 32 | 33 | 34 | #------------------------------------------------------------------------------# 35 | # Question 2 36 | 37 | ''' 38 | Write an algorithm to calculate the sample standard deviation of a onedimensional 39 | array of numbers where the sample standard deviation is 40 | defi ned to be the square root of the sample variance. 41 | ''' 42 | 43 | def FindSampleStandartDeviation(list): 44 | # Finding the sample variance 45 | variance = findSampleVariance(list) 46 | 47 | # return the standart deviation 48 | return sqrt(variance) 49 | 50 | #------------------------------------------------------------------------------# 51 | 52 | # Question 3 53 | 54 | ''' 55 | Write an algorithm to fi nd the median of a sorted one-dimensional array. 56 | (Be sure to handle arrays holding an even or odd number of items.) 57 | ''' 58 | 59 | def FindMedian(list): 60 | 61 | if (len(list) % 2 == 0): 62 | # The array has even length 63 | # Return the average of the two middle items 64 | middle = len(list) / 2 65 | return (list[middle -1] + list[middle]) / 2 66 | 67 | else: 68 | # The array has odd length 69 | # Return the middle item 70 | middle = len(list) - 1 / 2 71 | return list[middle] 72 | 73 | 74 | 75 | 76 | #------------------------------------------------------------------------------# 77 | 78 | # Question 4 79 | 80 | ''' 81 | The section “Removing Items” explained how to remove an item from a 82 | linear array. Write the algorithm in pseudocode. 83 | ''' 84 | def RemoveItem(list, index): 85 | # Slide items left 1 position to fill in where the item is 86 | 87 | for i in range(index, len(list) - 1): 88 | list[i - 1] = list[i] 89 | 90 | 91 | 92 | #------------------------------------------------------------------------------# 93 | 94 | # Question 5 95 | 96 | ''' 97 | The triangular arrays discussed in this chapter are sometimes called “lower 98 | triangular arrays” because the values are stored in the lower-left half of 99 | the array. How would you modify that kind of array to produce an upper 100 | triangular array with the values stored in the upper-right corner? 101 | ''' 102 | def FindIndex(r,c): 103 | return ((r - 1) * (r - 1) + (r - 1)) / 2 + c 104 | 105 | def FindIndex(r,c): 106 | return ((c - 1) * (c - 1) + (c - 1)) / 2 + r 107 | #------------------------------------------------------------------------------# 108 | 109 | # Question 6 110 | 111 | ''' 112 | How would you modify the lower triangular arrays described in this 113 | chapter to make an “upper-left” array where the entries are stored in the 114 | upper-left half of the array? What is the relationship between row and 115 | column for the entries in the array? 116 | ''' 117 | 118 | def FindIndex(r, c): 119 | r = N - 1 - r 120 | return ((r - 1) * (r - 1) + (r - 1)) / 2 + c 121 | 122 | 123 | 124 | #------------------------------------------------------------------------------# 125 | # Question 7 126 | 127 | ''' 128 | Suppose you defi ne the main diagonal of a rectangular (and nonsquare) 129 | array to start in the upper-left corner and extend down and to the right 130 | until it reaches the bottom or right edge of the array. Write an algorithm 131 | that fi lls entries on or below the main diagonal with 1s and entries above 132 | the main diagonal with 0s. 133 | ''' 134 | 135 | def FillListLLtoUR(values[,], ll_value, ur_value): 136 | for row in values: 137 | for col in values: 138 | if row >= col : 139 | values[row, col] = ur_value 140 | else: 141 | values[row, col] = ll_value 142 | 143 | #------------------------------------------------------------------------------# 144 | 145 | # Question 9 146 | 147 | ''' 148 | Write an algorithm that fi lls each item in a rectangular array with the 149 | distance from that entry to the nearest edge of the array. 150 | ''' 151 | 152 | def FillListWithDistances(values[,]): 153 | max_row = values.GetUpperBound(0) 154 | max_col = values.GetUpperBound(1) 155 | 156 | for row in range(max_row): 157 | for col in range(max_col): 158 | values[row, col] = Minimum(row, col, max_row - row, max_col - col) 159 | 160 | 161 | 162 | #------------------------------------------------------------------------------# 163 | 164 | #Question 10 165 | 166 | ''' 167 | *Generalize the method for building triangular arrays to build threedimensional 168 | tetrahedral arrays that contain entries value[i, j, k] where 169 | j ≤ i and k ≤ j. How would you continue to extend this method for even 170 | higher dimensions? 171 | ''' 172 | 173 | def NumCellsForTriangleRows(rows): 174 | return (rows * rows + rows ) / 2 175 | 176 | def NumCellsForTetrahedralRows(rows): 177 | return (rows * rows * rows + 3 * rows * rows + 2 * rows) / 6 178 | 179 | def RowColumnHeightToIndex(row, col, hgt): 180 | return NumCellsForTriangleRows + NumCellsForTetrahedralRows +hgt 181 | 182 | 183 | #------------------------------------------------------------------------------# 184 | 185 | 186 | # Question 12 187 | 188 | ''' 189 | Write an algorithm that adds two triangular arrays. 190 | 191 | ''' 192 | 193 | def AddTriangularLists(list1, list2 , result): 194 | for row in list1: 195 | for col in list2: 196 | result[row, col] = list1[row,col] + list2[row, col] 197 | 198 | 199 | #------------------------------------------------------------------------------# 200 | 201 | # Question 13 202 | 203 | ''' 204 | Write an algorithm that multiplies two triangular arrays. 205 | 206 | ''' 207 | 208 | def MultiplyLists(list1, list2, result): 209 | for i in list1: 210 | for j in list2: 211 | # Calculate the [i, j] result 212 | result[i, j] = 0 213 | for k in list2: 214 | resutl[i, j] = result[i, j] + list1[i,k] * list2[k,j] 215 | 216 | 217 | #------------------------------------------------------------------------------# 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | -------------------------------------------------------------------------------- /#5_Stacks_Queues.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eneskemalergin/Essential_Algorithms/bd59434b5d940c334694c623ed212e120ea171da/#5_Stacks_Queues.py -------------------------------------------------------------------------------- /#6_Sorting.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eneskemalergin/Essential_Algorithms/bd59434b5d940c334694c623ed212e120ea171da/#6_Sorting.py -------------------------------------------------------------------------------- /#7_Searching.py: -------------------------------------------------------------------------------- 1 | # -*- coding: cp1252 -*- 2 | # Chapter 7 # 3 | #------------------------------------------------------------------------------# 4 | # Question 1 5 | ''' Write a program that implements linear search. ''' 6 | def linearSearch(list, target): 7 | for i in range(len(list) -1): 8 | # if the target is int the ith element, return True 9 | if list[i] == target: 10 | return True 11 | return False # If not found, return false 12 | 13 | #------------------------------------------------------------------------------# 14 | # Question 4 15 | ''' Write a program that implements binary search. ''' 16 | def binarySearch(list, target): 17 | # Start with the entire sequence of elements 18 | low = 0 19 | high = len(list) - 1 20 | # We need to sort the list first 21 | list = list.sort() 22 | # Repeatedly subdivide the sequence in half until the target is found 23 | while low <= high: 24 | # find the midpoint of the sequence 25 | mid = (high+low) // 2 26 | # Does the midpoint contain the target? 27 | if list[mid] == target: 28 | return True 29 | # or does the target precede the midpoint? 30 | elif target < list[mid]: 31 | high = mid - 1 32 | else: 33 | low = mid - 1 34 | return False 35 | 36 | #------------------------------------------------------------------------------# 37 | # Question 6 38 | ''' Write a program that implements interpolation search. ''' 39 | 40 | def interpolationSearch(list, target): 41 | min = 0 42 | max = len(list) - 1 43 | while min <= max: 44 | # find the dividing item 45 | mid = min + (max - min) * (target - list[min])/(list[max]- list[min]) 46 | 47 | if list[mid] == target: 48 | return mid 49 | 50 | -------------------------------------------------------------------------------- /A_To_The_Power_Of_P.py: -------------------------------------------------------------------------------- 1 | # Calculate A to the power of P 2 | 3 | def RaiseToPower(): 4 | a = eval(input("Number you want to take power")) 5 | p = eval(input("Power:")) 6 | i = 1 7 | result = 1 8 | while (p >= 1): 9 | if (p % 2) == 1: 10 | result = result * a 11 | 12 | p = p/2 13 | a = a * a 14 | 15 | return result 16 | # Implement This 17 | ''' 18 | // Calculate A to the power P. 19 | Float: RaiseToPower(Float: A, Integer: P) 20 | P> 22 | 23 | Return AP 24 | End RaiseToPower 25 | ''' 26 | -------------------------------------------------------------------------------- /Advanced_DLL.py: -------------------------------------------------------------------------------- 1 | # Copied from internet, Author name is below: 2 | __author__ = "Adam Traub" 3 | __date__="2/16/2011" 4 | 5 | 6 | class LinkedList: 7 | '''Linked List''' 8 | class __Node: 9 | ''' 10 | private node object. Node's consist of an element 11 | and a pointer to the previous and next Node''' 12 | def __init__(self, element=None): 13 | self.__element = element 14 | self.__next = None 15 | self.__previous = None 16 | self.__toMove = (self.getPrevious,self.getNext) 17 | 18 | def __str__(self): 19 | '''string representation of Node''' 20 | return str(self.__element) 21 | 22 | def hasNext(self): 23 | '''returns true if the Node has a next Node''' 24 | return self.__next != None 25 | 26 | def getNext(self): 27 | '''get next Node''' 28 | return self.__next 29 | 30 | def setNext(self,nextItem): 31 | '''set the next Node of the Node''' 32 | self.__next = nextItem 33 | 34 | def hasPrevious(self): 35 | '''returns true if the Node has a previous Node''' 36 | return self.__previous != None 37 | 38 | def getPrevious(self): 39 | '''get previous Node''' 40 | return self.__previous 41 | 42 | def setPrevious(self,previousItem): 43 | '''set the previous Node of the Node''' 44 | self.__previous = previousItem 45 | 46 | def getPreviousAndNext(self): 47 | '''gets previous and next Nodes''' 48 | return self.__previous,self.__next 49 | 50 | def setPreviousAndNext(self, previousItem, nextItem): 51 | '''set the previous and Next Node of the Node''' 52 | self.__previous = previousItem 53 | self.__next = nextItem 54 | 55 | def getElement(self): 56 | '''get the element of the Node''' 57 | return self.__element 58 | 59 | def setElement(self, element): 60 | '''set the element of the current Node''' 61 | self.__element = element 62 | 63 | def get(self,gettingNextElement): 64 | '''Get element based on a boolean. True for next. False for previous''' 65 | return self.__toMove[int(gettingNextElement)]() 66 | 67 | 68 | def __init__(self): 69 | '''Creates the LinkedList''' 70 | self.__first = LinkedList.__Node() 71 | self.__last = self.__first 72 | self.__length = 0 73 | 74 | def __len__(self): 75 | '''returns the length of the list O(1)''' 76 | return self.__length 77 | 78 | def count(self): 79 | '''returns the length of the list O(1)''' 80 | return self.__length 81 | 82 | def isEmpty(self): 83 | '''returns true if the list is empty''' 84 | return self.__length == 0 85 | 86 | def append(self, element): 87 | '''Add element to last position of the list''' 88 | self.__handleLinking(LinkedList.__Node(element),self.__last,None,False) 89 | 90 | def pop(self, index =None): 91 | '''Removes and returns an element in the list. last element by default.''' 92 | if self.__length == 0: 93 | raise IndexError("pop from empty list") 94 | 95 | #utilize default parameter 96 | if index ==None: 97 | index = self.__length-1 98 | 99 | toRemove = self.__getNodeAtPosition(self.__checkIndex(index)) 100 | self.__handleLinking(toRemove,toRemove.getPrevious(),toRemove.getNext(),True) 101 | return toRemove.getElement() 102 | 103 | def insert(self, index, element): 104 | '''inserts an element to the given index''' 105 | toMove = self.__getNodeAtPosition(self.__checkIndex(index)) 106 | self.__handleLinking(LinkedList.__Node(element),toMove.getPrevious(),toMove,False) 107 | 108 | def extend(self, toAdd): 109 | '''extend current list by adding an iterable structure to the end''' 110 | for value in toAdd: 111 | self.append(value) 112 | 113 | def index(self, x): 114 | '''Find index of first ocurrence of a given value''' 115 | for dex,value in enumerate(self): 116 | if x == value: 117 | return dex 118 | raise ValueError("LinkedList.index(x): x not in list") 119 | 120 | def reverse(self): 121 | '''reverse the linked list''' 122 | for index in range(self.__length-1,-1,-1): 123 | self.append(self.pop(index)) 124 | 125 | def __getitem__(self, index): 126 | '''Allows for indexing, index must be an integer''' 127 | #accounts for slicing 128 | if type(index) == slice: 129 | return self.__sliceList(index) 130 | return self.__getNodeAtPosition(self.__checkIndex(index)).getElement() 131 | 132 | def __add__(self, other): 133 | '''adds a an iterable data structure to the linked list''' 134 | retList = LinkedList() 135 | for item in self: 136 | retList.append(item) 137 | for item in other: 138 | retList.append(item) 139 | return retList 140 | 141 | def __setitem__(self, index, element): 142 | '''Sets the item at a given index to a new element.''' 143 | self.__getNodeAtPosition(self.__checkIndex(index)).setElement(element) 144 | 145 | def __str__(self): 146 | '''returns a string representation of the list''' 147 | if self.__length == 0: 148 | return '[]' 149 | retString = "[" 150 | currentElement = self.__first.getNext() 151 | for i in range(self.__length): 152 | retString += str(currentElement) +", " 153 | currentElement = currentElement.getNext() 154 | 155 | return retString[:-2] + ']' 156 | 157 | 158 | #Private functions 159 | def __handleLinking(self, center, previous, nextNode, isRemoving): 160 | '''takes care of linking Nodes on inserts and removals''' 161 | def updateLinks(center, previous, nextNode, newNext, newLast, newPrevious, toAdd): 162 | '''A nested function to reduce repeated code in setting links''' 163 | if previous != None: 164 | previous.setNext(newNext) 165 | 166 | if nextNode == None: 167 | self.__last = newLast 168 | else: 169 | nextNode.setPrevious(newPrevious) 170 | self.__length += toAdd 171 | 172 | 173 | if isRemoving: 174 | updateLinks(center, previous, nextNode, nextNode, previous, previous, -1) 175 | else: 176 | center.setPreviousAndNext(previous,nextNode) 177 | updateLinks(center, previous, nextNode, center, center, center, 1) 178 | 179 | 180 | def __sliceList(self,theSlice): 181 | '''(Private) function to handle slicing. Returns a Linked List''' 182 | def determineStartStopStep(valToCheck, step, positiveStep, negativeStep): 183 | '''nested function to reduce repeated code in determining slicing handling''' 184 | if valToCheck == None: 185 | if step > 0: 186 | return positiveStep 187 | else: 188 | return negativeStep 189 | else: 190 | return valToCheck 191 | 192 | 193 | retList = LinkedList() 194 | #Following conditions handles the x[start:stop:step] notation 195 | step = determineStartStopStep(theSlice.step,1,1,1) 196 | start = determineStartStopStep(theSlice.start,step,0,self.__length-1) 197 | stop = determineStartStopStep(theSlice.stop,step,self.__length,-1) 198 | 199 | currentNode = self.__getNodeAtPosition(start) 200 | gettingNext = step > 0 201 | absStep = abs(step) 202 | 203 | for eachItem in range(start,stop,step): 204 | retList.append(currentNode) 205 | if eachItem + step <= stop:#prevents step from going out of bounds 206 | for i in range(absStep): 207 | currentNode = currentNode.get(gettingNext) 208 | return retList 209 | 210 | 211 | 212 | def __getNodeAtPosition(self, index): 213 | '''(Private) Gets a Node at a given index''' 214 | movingForward = index < (self.__length//2)-1 215 | if movingForward: 216 | currentNode = self.__first 217 | toAdd = 1 218 | else: 219 | currentNode = self.__last 220 | index = (self.__length-1) - index 221 | toAdd = 0 222 | 223 | """ 224 | Putting the for loop inside the condition would reduce the amount 225 | of times the conditon must be evaluated, increasing efficiency 226 | But would also simultaneously increase the amount of repeated code 227 | """ 228 | for i in range(index+toAdd): 229 | currentNode = currentNode.get(movingForward) 230 | 231 | return currentNode 232 | 233 | def __checkIndex(self, index): 234 | '''(Private) check if the index is an acceptable value. Index only changes if negative''' 235 | if type(index) != int: 236 | raise TypeError("Index must be an integer or a slice not a "+str(type(index)).split("'")[1]) 237 | 238 | #handles negative indices. 239 | if index < 0: 240 | index += self.__length 241 | 242 | #If the index is out of bounds 243 | if index >= self.__length or index < 0: 244 | raise IndexError("Index out of bounds") 245 | 246 | return index 247 | 248 | if __name__ == "__main__": 249 | import random 250 | def advanceWMessage(message): 251 | input(message+" press enter to continue") 252 | def printList(theList): 253 | print("Current List:"+str(theList)) 254 | 255 | x = LinkedList() 256 | for i in range(30): 257 | x.append(i) 258 | 259 | printList(x) 260 | advanceWMessage("Testing slicing") 261 | for i in range(10): 262 | val1 = random.randint(0,len(x)//2) 263 | val2 = random.randint(len(x)//2,len(x)) 264 | val3 = random.randint(1,len(x)//10) 265 | print("\n\nstart: "+str(val1)) 266 | print("stop: "+str(val2)) 267 | print("step: "+str(val3)) 268 | print(x[val1:val2:val3]) 269 | 270 | advanceWMessage("Insert -1 at beginning") 271 | x.insert(0,-1) 272 | printList(x) 273 | 274 | 275 | 276 | -------------------------------------------------------------------------------- /Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """ 3 | Tree node: left and right child + data which can be any object 4 | """ 5 | def __init__(self, data): 6 | """ 7 | Node constructor 8 | @param data node data object 9 | """ 10 | self.left = None 11 | self.right = None 12 | self.data = data 13 | def insert(self, data): 14 | """ 15 | Insert new node with data 16 | @param data node data object to insert 17 | """ 18 | if data < self.data: 19 | if self.left is None: 20 | self.left = Node(data) 21 | else: 22 | self.left.insert(data) 23 | elif data > self.data: 24 | if self.right is None: 25 | self.right = Node(data) 26 | else: 27 | self.right.insert(data) 28 | def lookup(self, data, parent=None): 29 | """ 30 | Lookup node containing data 31 | @param data node data object to look up 32 | @param parent node's parent 33 | @returns node and node's parent if found or None, None 34 | """ 35 | if data < self.data: 36 | if self.left is None: 37 | return None, None 38 | return self.left.lookup(data, self) 39 | elif data > self.data: 40 | if self.right is None: 41 | return None, None 42 | return self.right.lookup(data, self) 43 | else: 44 | return self, parent 45 | def delete(self, data): 46 | """ 47 | Delete node containing data 48 | @param data node's content to delete 49 | """ 50 | # get node containing data 51 | node, parent = self.lookup(data) 52 | if node is not None: 53 | children_count = node.children_count() 54 | if children_count == 0: 55 | # if node has no children, just remove it 56 | if parent.left is node: 57 | parent.left = None 58 | else: 59 | parent.right = None 60 | del node 61 | elif children_count == 1: 62 | # if node has 1 child 63 | # replace node by its child 64 | if node.left: 65 | n = node.left 66 | else: 67 | n = node.right 68 | if parent: 69 | if parent.left is node: 70 | parent.left = n 71 | else: 72 | parent.right = n 73 | del node 74 | else: 75 | # if node has 2 children 76 | # find its successor 77 | parent = node 78 | successor = node.right 79 | while successor.left: 80 | parent = successor 81 | successor = successor.left 82 | # replace node data by its successor data 83 | node.data = successor.data 84 | # fix successor's parent node child 85 | if parent.left == successor: 86 | parent.left = successor.right 87 | else: 88 | parent.right = successor.right 89 | def compare_trees(self, node): 90 | """ 91 | Compare 2 trees 92 | @param node tree to compare 93 | @returns True if the tree passed is identical to this tree 94 | """ 95 | if node is None: 96 | return False 97 | if self.data != node.data: 98 | return False 99 | res = True 100 | if self.left is None: 101 | if node.left: 102 | return False 103 | else: 104 | res = self.left.compare_trees(node.left) 105 | if res is False: 106 | return False 107 | if self.right is None: 108 | if node.right: 109 | return False 110 | else: 111 | res = self.right.compare_trees(node.right) 112 | return res 113 | def print_tree(self): 114 | """ 115 | Print tree content inorder 116 | """ 117 | if self.left: 118 | self.left.print_tree() 119 | print self.data, 120 | if self.right: 121 | self.right.print_tree() 122 | def tree_data(self): 123 | """ 124 | Generator to get the tree nodes data 125 | """ 126 | # we use a stack to traverse the tree in a non-recursive way 127 | stack = [] 128 | node = self 129 | while stack or node: 130 | if node: 131 | stack.append(node) 132 | node = node.left 133 | else: # we are returning so we pop the node and we yield it 134 | node = stack.pop() 135 | yield node.data 136 | node = node.right 137 | def children_count(self): 138 | """ 139 | Return the number of children 140 | @returns number of children: 0, 1, 2 141 | """ 142 | cnt = 0 143 | if self.left: 144 | cnt += 1 145 | if self.right: 146 | cnt += 1 147 | return cnt 148 | -------------------------------------------------------------------------------- /Binary Search.py: -------------------------------------------------------------------------------- 1 | def search(sequence, number, lower, upper): 2 | if lower == upper: 3 | assert number == sequence[upper] 4 | return upper 5 | else: 6 | middle = (lower + upper) // 2 7 | if number > sequence[middle]: 8 | return search(sequence, number, middle+1, upper) 9 | else: 10 | return search(sequence, number, lower, middle) 11 | 12 | def search(sequence, number): 13 | if len(sequence) == 1: 14 | return number 15 | else: 16 | 17 | -------------------------------------------------------------------------------- /BinarySearch_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Binary Search ''' 2 | def binarySearch(list, target): 3 | # Start with the entire sequence of elements 4 | low = 0 5 | high = len(list) - 1 6 | # We need to sort the list first 7 | list = list.sort() 8 | # Repeatedly subdivide the sequence in half until the target is found 9 | while low <= high: 10 | # find the midpoint of the sequence 11 | mid = (high+low) // 2 12 | # Does the midpoint contain the target? 13 | if list[mid] == target: 14 | return True 15 | # or does the target precede the midpoint? 16 | elif target < list[mid]: 17 | high = mid - 1 18 | else: 19 | low = mid - 1 20 | return False 21 | 22 | 23 | list = [12, 5, 13, 8, 9, 65] 24 | print binarySearch(list, 9) 25 | 26 | # Something Wrong 27 | -------------------------------------------------------------------------------- /CountTheDifference.py: -------------------------------------------------------------------------------- 1 | count = input() 2 | List = map(int, input().split) 3 | List.sort() 4 | 5 | dif = abs(List[0] - List[1]) 6 | for i in range(0, len(List)-1): 7 | if dif > abs(List[i+1] - List[i]): 8 | dif = abs(List[i+1] - List[i]) 9 | 10 | for i in range(0, len(List) - 1): 11 | if dif == abs(List[i+1] - List[i]): 12 | print List[i], List[i+1], 13 | -------------------------------------------------------------------------------- /CountingSort_Algorithm.py: -------------------------------------------------------------------------------- 1 | def countingsort(alist): 2 | counts = [] 3 | for i in range(100): 4 | counts.append(0) 5 | for i in alist: 6 | counts[i] += 1 7 | 8 | sortedList = [] 9 | for i in range(100): 10 | if counts[i] > 0: 11 | for j in range(counts[i]): 12 | sortedList.append(i) 13 | 14 | return sortedList 15 | 16 | 17 | print(countingsort([2,16,77,65, 99, 4, 2, 16, 16])) 18 | #expected [2,2,4,16,16,16,65,77,99] 19 | -------------------------------------------------------------------------------- /CountingSort_Algorithm2.py: -------------------------------------------------------------------------------- 1 | ''' Counting Sort ''' 2 | def CountingSort(list, max_value): 3 | # Make and array to hold the counts 4 | counts = [] 5 | 6 | # Initialize the array to hold the counts. 7 | for i in range(max_value): 8 | counts.append(0) 9 | 10 | # Count the items with each value 11 | for j in list: 12 | # Add 1 to the count for this value 13 | counts[j] += 1 14 | 15 | sortedList = [] 16 | for i in range(max_value): 17 | if counts[i] > 0: 18 | for j in range(counts[i]): 19 | sortedList.append(i) 20 | 21 | return sortedList 22 | print(CountingSort([2,16,77,65, 99, 4, 2, 16, 16], 100)) 23 | #expected [2,2,4,16,16,16,65,77,99] 24 | -------------------------------------------------------------------------------- /DLL_another.py: -------------------------------------------------------------------------------- 1 | # Implementation of Doubly linked Lists from different sources and with different styles 2 | # An implementation of doubly linked list 3 | 4 | class ListNode: 5 | def __init__(self, data): 6 | self.data = data 7 | self.next = self.previous = None 8 | 9 | class List: 10 | def __init__(self): 11 | self.head = self.tail = None 12 | 13 | def addFirstNode(self, newNode): 14 | ''' A function to add the first node to the list ''' 15 | 16 | self.head = self.tail = newNode 17 | self.head.previous = self.tail.next = None 18 | 19 | def addNodeTail(self, data): 20 | ''' Function to add an element to the tail of the list ''' 21 | 22 | newNode = ListNode(data) 23 | 24 | # Empty list 25 | if self.head == None: 26 | self.addFirstNode(newNode) 27 | 28 | # Non-empty list 29 | else: 30 | self.tail.next = newNode 31 | newNode.previous = self.tail 32 | self.tail = newNode 33 | 34 | self.tail.next = None 35 | 36 | def addNodeHead(self, data): 37 | ''' Function to add an element to the head of the list ''' 38 | 39 | newNode = ListNode(data) 40 | 41 | # Empty list 42 | if self.head == None: 43 | self.addFirstNode(newNode) 44 | 45 | # Non-empty list 46 | else: 47 | self.head.previous = newNode 48 | newNode.next = self.head 49 | self.head = newNode 50 | 51 | def delFirstNode(self): 52 | ''' Funtion to delete the single node ''' 53 | 54 | self.previous = self.next = self.head = self.tail = None 55 | 56 | def delNodeTail(self): 57 | ''' Function to delete an element from the list ''' 58 | 59 | node = self.tail 60 | 61 | # Empty list 62 | if self.head == None: 63 | print "List is empty" 64 | return 65 | 66 | # Single node list 67 | elif self.head == self.tail: 68 | self.delFirstNode() 69 | return 70 | 71 | # Multiple node list 72 | else: 73 | self.tail = node.previous 74 | self.tail.next = None 75 | 76 | def delNodeHead(self): 77 | ''' Function to delete a node from head ''' 78 | 79 | node = self.head 80 | 81 | # Empty list 82 | if self.head == None: 83 | print "List is empty" 84 | return 85 | 86 | # Single node list 87 | if self.head == self.tail: 88 | self.delFirstNode() 89 | return 90 | 91 | # Multi-node list 92 | if self.head != self.tail: 93 | node = node.next 94 | node.previous = None 95 | self.head = node 96 | 97 | def delNode(self, element): 98 | ''' Function to delete a user specified node ''' 99 | 100 | node = self.head 101 | found = False 102 | 103 | # Single node and element is present 104 | if self.head == self.tail and self.head.data != element: 105 | print "Element not found in the list" 106 | return 107 | 108 | # Head contains element 109 | if self.head.data == element: 110 | self.delNodeHead() 111 | 112 | # Checks for the element in the list 113 | while node.next != None: 114 | if node.next.data == element: 115 | found = True 116 | break 117 | else: 118 | node = node.next 119 | 120 | # If element was found 121 | if found: 122 | if node.next.next != None: 123 | temp = node.next 124 | node.next = temp.next 125 | node = temp.next.previous 126 | 127 | else: 128 | self.delNodeTail() 129 | 130 | # If the element was not found 131 | else: 132 | print "Element was not found in the list" 133 | 134 | 135 | 136 | def display(list): 137 | ''' Function to display the linked list ''' 138 | 139 | print "\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+" 140 | node = list.head 141 | if list.head == None: 142 | print "Head -> None ", 143 | while node is not None: 144 | print " %d " % (node.data), 145 | node = node.next 146 | if node is not None: 147 | print "", 148 | print " <- Tail", 149 | print "\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" 150 | 151 | 152 | if __name__ == "__main__": 153 | ''' Main function ''' 154 | 155 | list = List() 156 | while True: 157 | print "+-+-+-+-+-+-+-+-+-Doubly Linked list+-+-+-+-+-+-+-+-+-+" 158 | print "+ 1. Add a node to the tail +" 159 | print "+ 2. Add a node to the head +" 160 | print "+ 3. Remove a node from tail +" 161 | print "+ 4. Remove a node from head +" 162 | print "+ 5. Remove a node +" 163 | print "+ 6. Exit +" 164 | print "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+" 165 | s = int(raw_input('Enter your Choice: ')) 166 | if s==1: 167 | inp = int(raw_input('Enter the element you want to insert to the tail: ')) 168 | list.addNodeTail(inp) 169 | display(list) 170 | 171 | elif s==2: 172 | inp = int(raw_input('Enter the element you want to insert to the head: ')) 173 | list.addNodeHead(inp) 174 | display(list) 175 | 176 | elif s==3: 177 | list.delNodeTail() 178 | display(list) 179 | 180 | elif s==4: 181 | list.delNodeHead() 182 | display(list) 183 | 184 | elif s==5: 185 | inp = int(raw_input('Enter the element you want to delete from the list: ')) 186 | list.delNode(inp) 187 | display(list) 188 | 189 | elif s==6: 190 | break; 191 | 192 | else: 193 | print "Invalid input" 194 | -------------------------------------------------------------------------------- /DP_flippingCoin.py: -------------------------------------------------------------------------------- 1 | 2 | def count(S, m, n): 3 | table = [[0 for x in range(m)] for x in range(n+1)] # Creating a table n+1 rows 4 | for i in range(m): # filling the entriest for 0 value case n = 0 5 | table[0][i] = 1 6 | 7 | for i in range(1 , n+1): # Filling rest of the table bottom-up manner 8 | for j in range(m): 9 | x = table[ i - S[j] ][j] if i-S[j] >= 0 else 0 # Count of solutions including S[j] 10 | y = table[i][j-1] if j >= 1 else 0 # Count of solutions excluding S[j] 11 | table[i][j] = x + y # total count 12 | 13 | return table[n][m-1] 14 | 15 | 16 | n,m = map(int, raw_input().split()) 17 | S = map(int, raw_input().split()) 18 | 19 | print(count(S,m,n)) 20 | -------------------------------------------------------------------------------- /Double_LinkedList_implementation_from_book.py: -------------------------------------------------------------------------------- 1 | # Implementatation of basic Double Linked List 2 | 3 | # Improvement of Double Linked list is: 4 | # You can search delete or reach from backwards. 5 | class Node: 6 | def __init__(self, value=None, next=None, prev=None): 7 | self.value = value 8 | self.next = next 9 | self.prev = prev # prev allows you to go back. 10 | 11 | def __str__(self): 12 | return str(self.value) 13 | 14 | 15 | def ShowPrevNext(node): 16 | print node.prev,"<--", node , "-->",node.next 17 | 18 | #Create nodes 19 | mynode1= Node("first") 20 | mynode2= Node("second") 21 | mynode3= Node("third") 22 | 23 | #link them 24 | mynode1.next = mynode2 25 | mynode2.next = mynode3 26 | 27 | mynode2.prev = mynode1 28 | mynode3.prev = mynode2 29 | 30 | ShowPrevNext(mynode2) # Shows next and prev node of it. 31 | 32 | def InsertCell(after_me, new_cell): 33 | #Update Next Links 34 | new_cell.next = after_me.next 35 | after_me.next = new_cell 36 | 37 | #Update prev links 38 | new_cell.next.prev = new_cell 39 | new_cell.prev = after_me 40 | 41 | 42 | new_node= Node("new one") 43 | InsertCell(mynode2, new_node) 44 | -------------------------------------------------------------------------------- /Exp(RegularOne).py: -------------------------------------------------------------------------------- 1 | def Exp(a, b): 2 | i = 1 3 | result = 1 4 | while (b >= 1): 5 | result = result * a 6 | b = b - 1 7 | return result 8 | # Working 9 | -------------------------------------------------------------------------------- /FindFactors(Improved).py: -------------------------------------------------------------------------------- 1 | #Finding Factors(Improved Algorithm) 2 | import math 3 | def FindFactors(number): 4 | factors = [] 5 | while(number % 2 == 0): 6 | factors.append(2) 7 | number = number / 2 8 | #End While 9 | 10 | #Looking for Odd factors 11 | i = 3 12 | max_factor = math.sqrt(number) 13 | while(i <= max_factor): 14 | while((number % i) == 0): 15 | # i is a factor add the list 16 | factors.append(i) 17 | 18 | # divide the number by i 19 | number = number / i 20 | 21 | # set a new upper bond 22 | 23 | max_factpr = math.sqrt(number) 24 | # End While 25 | 26 | # Checks next ODD number 27 | i = i + 2 28 | 29 | # End While 30 | 31 | if (number > 1): 32 | factors.append(number) 33 | return factors 34 | -------------------------------------------------------------------------------- /FindFactors.py: -------------------------------------------------------------------------------- 1 | #Finding Prime Factors (Basic Version) 2 | 3 | def FindFactors(number): 4 | my_list = [] 5 | i = 2 6 | while(i <= number): 7 | while(number % i == 0): 8 | my_list.append(i) 9 | number = number / i 10 | i = i + 1 11 | 12 | # It adds any number left, it's also a factor 13 | if (number > 1): 14 | my_list.append(number) 15 | return my_list 16 | # To Remove the duplicates 17 | # return list(set(my_list)) 18 | 19 | 20 | -------------------------------------------------------------------------------- /FindPrimes.py: -------------------------------------------------------------------------------- 1 | author: @nadide 2 | from math import sqrt 3 | def FindPrimes (max_number): 4 | 5 | is_composite = [] 6 | 7 | for i in range(4,max_number+1,2): 8 | is_composite[i] = True 9 | 10 | next_prime = 3 11 | stop_at = int(sqrt(max_number)) 12 | while (next_prime < stop_at): 13 | #print next_prime 14 | for i in range(next_prime*2,max_number+1,next_prime): 15 | is_composite[i] = True 16 | next_prime += 2 17 | while (next_prime <= max_number and is_composite[next_prime]): 18 | next_prime += 2 19 | 20 | primes = [] 21 | for i in range(2,max_number+1): 22 | if (not is_composite[i]): 23 | primes.append(i) 24 | 25 | return primes 26 | 27 | -------------------------------------------------------------------------------- /Finding Factors Fast.py: -------------------------------------------------------------------------------- 1 | #Finding Factors Fast 2 | def FindingFactorsFast(number): 3 | factors = [] 4 | 5 | while(number % 2 == 0): 6 | factors.append(2) 7 | number = number / 2 8 | 9 | i = 3 10 | max_factor = number ** 0.5 # sqrt(number) 11 | while(i <= max_factor): 12 | while(number % i == 0): 13 | factors.append(i) 14 | number = number / i 15 | 16 | -------------------------------------------------------------------------------- /Finding Factors.py: -------------------------------------------------------------------------------- 1 | def FindFactors(number): 2 | factors = [] 3 | i = 2 4 | while (i < number): 5 | while(number % i == 0): 6 | factors.append(i) 7 | number = number / i 8 | i = i + 1 9 | if(number > 1): 10 | factors.append(number) 11 | return factors 12 | 13 | print(FindFactors(1204)) 14 | -------------------------------------------------------------------------------- /GCD Algorithm.py: -------------------------------------------------------------------------------- 1 | a = 876 2 | b = 1587 3 | def GCD(a, b): 4 | while (b != 0): 5 | remainder = a % b 6 | a = b 7 | b = remainder 8 | return a 9 | -------------------------------------------------------------------------------- /GCD(Great Common Divisor).py: -------------------------------------------------------------------------------- 1 | # Using Python 2 | # This is for already defined 2 values 3 | '''def GCD(a, b): 4 | while (b != 0): 5 | remainder = a % b 6 | a = b 7 | b = remainder 8 | return a 9 | ''' 10 | # We are asking user to put input 11 | a = input() 12 | b = input() 13 | 14 | # Returns the greatest common divisor of two numbers 15 | def GCD(a,b): 16 | while(b != 0): 17 | remainder = a % b 18 | a = b 19 | b = remainder 20 | return a 21 | 22 | # Returns only two numbers least common multiplier 23 | def LCM(a,b): 24 | return ((a * b) / GCD(a,b)) 25 | 26 | 27 | # Returns many different numbers' least common multiplier 28 | def LCMM(*args): 29 | return reduce(GCDLCM, args) 30 | 31 | print (GCD(a,b)) 32 | print (LCM(a,b)) 33 | -------------------------------------------------------------------------------- /Gnome_Sort.py: -------------------------------------------------------------------------------- 1 | ## Author: Enes Kemal Ergin 2 | ## Date : 02/02/15 3 | 4 | def gnomesort(seq): 5 | i = 0 6 | while i < len(seq): 7 | if i == 0 or seq[i-1] <= seq[i]: 8 | i+= 1 9 | else: 10 | seq[i], seq[i-1] = seq[i-1], seq[i] 11 | i -= 1 12 | return seq 13 | 14 | # test 1 15 | seq = [1,4,5,7,12,3,4,7,8,10,2,6,87,98] 16 | print(gnomesort(seq)) 17 | -------------------------------------------------------------------------------- /Huge_IsPrime_Miller_Rabin.py: -------------------------------------------------------------------------------- 1 | ## Code from: rosettacode.org 2 | # This algorithm for huge numbers' testing. 3 | def _try_composite(a, d, n, s): 4 | if pow(a, d, n) == 1: 5 | return False 6 | for i in range(s): 7 | if pow(a, 2**i * d, n) == n-1: 8 | return False 9 | return True # n is definitely composite 10 | 11 | def is_prime(n, _precision_for_huge_n=16): 12 | if n in _known_primes or n in (0, 1): 13 | return True 14 | if any((n % p) == 0 for p in _known_primes): 15 | return False 16 | d, s = n - 1, 0 17 | while not d % 2: 18 | d, s = d >> 1, s + 1 19 | # Returns exact according to http://primes.utm.edu/prove/prove2_3.html 20 | if n < 1373653: 21 | return not any(_try_composite(a, d, n, s) for a in (2, 3)) 22 | if n < 25326001: 23 | return not any(_try_composite(a, d, n, s) for a in (2, 3, 5)) 24 | if n < 118670087467: 25 | if n == 3215031751: 26 | return False 27 | return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7)) 28 | if n < 2152302898747: 29 | return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11)) 30 | if n < 3474749660383: 31 | return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13)) 32 | if n < 341550071728321: 33 | return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17)) 34 | # otherwise 35 | return not any(_try_composite(a, d, n, s) 36 | for a in _known_primes[:_precision_for_huge_n]) 37 | 38 | _known_primes = [2, 3] 39 | _known_primes += [x for x in range(5, 1000, 2) if is_prime(x)] 40 | 41 | 42 | ## Tests 43 | is_prime(4547337172376300111955330758342147474062293202868155909489) # True 44 | is_prime(4547337172376300111955330758342147474062293202868155909393) # False 45 | [x for x in range(901, 1000) if is_prime(x)] 46 | is_prime(643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153) 47 | -------------------------------------------------------------------------------- /Insertion_sorted_list.py: -------------------------------------------------------------------------------- 1 | # Inserting an item into a sorted singly linked list: 2 | 3 | ''' 4 | This is very useful to add item to list in position that it needs to be in 5 | ''' 6 | def InsertCell(top, new_cell): 7 | #Find the cell before where the new cell belongs 8 | while (top.next != None) and (top.next.value < new_cell.value): 9 | top = top.next 10 | #insert The cell after top 11 | 12 | new_cell.next = top.next 13 | top.next = new_cell 14 | 15 | # following function do the same as the one above with sentinel; 16 | def InsertCellWithSentinel(top, new_cell): 17 | #Find the cell before where the new cell belongs 18 | while(top.next.value < new_cell.value): 19 | top = top.next 20 | 21 | # Insert the new cell after top 22 | new_cell.next = top.next 23 | top.next = new_cell 24 | 25 | -------------------------------------------------------------------------------- /InterpolationSearch_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Interpolation Search ''' 2 | 3 | def interpolationSearch(list, target): 4 | min = 0 5 | max = len(list) - 1 6 | while min <= max: 7 | # find the dividing item 8 | mid = min + (max - min) * (target - list[min])/(list[max]- list[min]) 9 | 10 | if list[mid] == target: 11 | return mid 12 | 13 | 14 | -------------------------------------------------------------------------------- /IsPrime.py: -------------------------------------------------------------------------------- 1 | # This function checks the number if it is prime or not... 2 | # Author : Enes Kemal Ergin 3 | # Date : 02/14/15 4 | # Return true if the number p is prime... 5 | import random 6 | def IsPrime(p, max_tests): 7 | # Perform the test up to max_tests times 8 | for i in range(max_tests): 9 | n = random.randint(1, p - 1) 10 | if (pow(n, p-1) % p) != 1: 11 | return False 12 | 13 | # If the loop finish executing and did not return False we got probably a prime. 14 | # There is pow(1/2,max_test) chance that it is not prime. 15 | return True 16 | 17 | ## Tests 18 | IsPrime(2,1) 19 | IsPrime(3,1) 20 | IsPrime(15,10) 21 | IsPrime(19,10) -------------------------------------------------------------------------------- /IsPrime_Miller_Rabin.py: -------------------------------------------------------------------------------- 1 | # This function is an imlementation of Miller-Rabin Primality Test. 2 | """ 3 | Miller-Rabin Primality test is the fastest algorithm so far for large n values. 4 | 5 | This algorithm is accepting as a breakthrough in the study of probabilistic algorithms. 6 | """ 7 | 8 | import random 9 | 10 | def decompose(n): 11 | exponentOfTwo = 0 12 | 13 | while n % 2 == 0: 14 | n = n/2 15 | exponentOfTwo += 1 16 | 17 | return exponentOfTwo, n 18 | 19 | def isWitness(possibleWitness, p, exponent, remainder): 20 | possibleWitness = pow(possibleWitness, remainder, p) 21 | 22 | if possibleWitness == 1 or possibleWitness == p - 1: 23 | return False 24 | 25 | for _ in range(exponent): 26 | possibleWitness = pow(possibleWitness, 2, p) 27 | 28 | if possibleWitness == p - 1: 29 | return False 30 | 31 | return True 32 | 33 | def probablyPrime(p, accuracy=100): 34 | if p == 2 or p == 3: return True 35 | if p < 2: return False 36 | 37 | numTries = 0 38 | exponent, remainder = decompose(p - 1) 39 | 40 | for _ in range(accuracy): 41 | possibleWitness = random.randint(2, p - 2) 42 | if isWitness(possibleWitness, p, exponent, remainder): 43 | return False 44 | 45 | return True -------------------------------------------------------------------------------- /LLStack_implementation_extra.py: -------------------------------------------------------------------------------- 1 | ''' Implementation of stack using a singly linked list ''' 2 | class LLStack: 3 | # Creates an empty stack 4 | def __init__(self): 5 | self._top = None 6 | self._size = 0 7 | 8 | # Returns True if the stack is empty 9 | def isEmpty(self): 10 | return self._top is None 11 | 12 | # Return the top item on the stack without removing it 13 | def peek(self): 14 | assert not self.isEmpty(), "Cannot peek at an empty stack" 15 | return self._top.item 16 | 17 | # Removes and returns the top item on the stack 18 | def pop(self): 19 | assert not self.isEmpty(), "Cannot pop from an empty stack" 20 | node = self._top 21 | self.top = self._top.next 22 | self._size -= 1 23 | return node.item 24 | 25 | # Pushes and item onto the top of the stack 26 | def push(self, item): 27 | self._top = _StackNode(item, self._top) 28 | self._size += 1 29 | # Private storage class for creating stack nodes 30 | class _StackNode: 31 | def __init__(self, item, link): 32 | self.item = item 33 | self.next = link 34 | 35 | -------------------------------------------------------------------------------- /LinearSearch_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Linear Search ''' 2 | def linearSearch(list, target): 3 | for i in range(len(list) -1): 4 | # if the target is int the ith element, return True 5 | if list[i] == target: 6 | return True 7 | return False # If not found, return false 8 | 9 | list = [12, 5, 13, 8, 9, 65] 10 | print linearSearch(list, 5) 11 | 12 | -------------------------------------------------------------------------------- /LinkedList.py: -------------------------------------------------------------------------------- 1 | 2 | class Node: 3 | def __init__(self, value = None, next = None): 4 | self.value = value 5 | self.next = next 6 | def __str__(self): 7 | return(str(self.value)) 8 | 9 | mynode1 = Node("1") 10 | mynode2 = Node("2") 11 | mynode3 = Node("3") 12 | 13 | mynode1.next = mynode2 14 | mynode2.next = mynode3 15 | 16 | def Iterate(top): 17 | while(top != None): 18 | print(top.Value) 19 | top = top.next 20 | # End While 21 | # End Iterate 22 | 23 | def FindCell(top, target): 24 | while(top != None): 25 | if(top.value == target): 26 | return (top) 27 | top = top.next 28 | # End While 29 | return None 30 | 31 | # End FindCell 32 | 33 | def FindCellBefore(top, target): 34 | if (top == None): 35 | return None 36 | # Search for the target Value 37 | while(top.next != None): 38 | if(top.next.Value2 == target): 39 | return (top) 40 | top = top.next 41 | # End While 42 | 43 | # If we get this far, the target is not in the list 44 | return None 45 | 46 | # End FindCellBefore 47 | 48 | # Modifiying the last code with usage of sentinel 49 | def FindCellBefore(top, target): 50 | # Search for the target value 51 | while(top.next != None): 52 | if (top.next.value == target): 53 | return (top) 54 | top = top.next 55 | # End While 56 | 57 | # If we get this far, the target is not in the list 58 | return None 59 | # End FindCellBefore 60 | 61 | ''' 62 | Following algorithm adds a new item at the beginning of a linked list 63 | ''' 64 | def AddAtBeginnig(top, new_cell): 65 | new_cell.next = top.next 66 | top.next = new_cell 67 | 68 | # End AddAtBeginning 69 | 70 | ''' 71 | Following algorithm adds a new item at the end of a linked list 72 | ''' 73 | def AddAtEnd(top, new_cell): 74 | # Find the last Cell. 75 | while(top.next != None): 76 | top = top.next 77 | # End wHile 78 | 79 | # Adds the new cell at the end 80 | top.next = new_cell 81 | new_cell.next = None 82 | # End AddAtEnd 83 | 84 | ''' 85 | If we want to insert and item after specific cell 86 | ''' 87 | 88 | def InsertCell(after_me, new_cell): 89 | new_cell.next = after_me.next 90 | after_me.next = new_cell 91 | # End InsertCell 92 | 93 | 94 | ''' 95 | Languages like java does not need to erase free cells 96 | they are using garbage collection system. 97 | If your language has something like garbage collection system 98 | use this function, otherwise next function will erase the free cells/ 99 | ''' 100 | def DeleteAfter(after_me): 101 | after_me.next = after_me.next.next 102 | # End DeleteAfter 103 | 104 | def DeleteAfter(after_me): 105 | target_cell = after_me.next 106 | after_me.next = after_me.next.next 107 | free(target_cell)#? 108 | # End DeleteAfter 109 | 110 | 111 | def DestroyList(top): 112 | while(top != None): 113 | # Save a Pointer to the next Cell 114 | next_cell = top.next 115 | 116 | # Free top. 117 | free(top) #? 118 | 119 | # move to the next cell 120 | top = next_cell 121 | # End While 122 | # End DestroyList 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | -------------------------------------------------------------------------------- /LinkedList_Queue.py: -------------------------------------------------------------------------------- 1 | # Linked-List Queues # 2 | 3 | def Enqueue(top_sentinel, new_value): 4 | # Make a cell to hold the new value 5 | new_cell = New Cell 6 | new_cell.value = new_value 7 | 8 | # Add the new cell to the linked list 9 | new_cell.next = top_sentinel.next 10 | top_sentinel.next = new_cell 11 | new_cell.prev = top_sentinel 12 | 13 | 14 | def Dequeue(bottom_sentinel): 15 | # Make sure there is an item to dequeue 16 | if (bottom_sentinel.prev == top.sentinel): 17 | return "Already Empty" 18 | else: 19 | # Get the bottom cell's value 20 | result = bottom_sentinel.prev.value 21 | 22 | # Remove the bottom cell from the linked list 23 | bottom_sentinel.prev = bottom_sentinel.prev.prev 24 | bottom_sentinel.prev.next = bottom_sentinel 25 | 26 | # Returns the result 27 | return result 28 | -------------------------------------------------------------------------------- /LinkedList_Queue_extra.py: -------------------------------------------------------------------------------- 1 | ''' Implementation iof the queue using linked list ''' 2 | class LLQueue: 3 | def __init__(self): 4 | self._qhead = None 5 | self._qtail = None 6 | self._count = None 7 | 8 | def isEmpty(self): 9 | return self._qhead is None 10 | 11 | def __len__(self): 12 | return self._count 13 | 14 | def enqueue(self, item): 15 | node = _QueueNode(item) 16 | if self.isEmpty(): 17 | self._qhead = None 18 | else: 19 | self._qtail = node 20 | 21 | self._qtail = node 22 | self._count += 1 23 | 24 | def dequeue(self): 25 | assert not self.isEmpty(), "Cannot dequeue from an empty queueu." 26 | node = self._qhead 27 | if self._qhead is self._qtail: 28 | self._qtail = None 29 | 30 | self._qhead = self.qhead.next 31 | self._count -= 1 32 | return node.item 33 | 34 | class _QueueNode(object): 35 | def __init__(self, item): 36 | self.item = item 37 | self.cext = None 38 | 39 | -------------------------------------------------------------------------------- /LinkedList_implementation_from_book.py: -------------------------------------------------------------------------------- 1 | # Lets implement a linked list 2 | class Node: 3 | def __init__(self, value=None, next=None): 4 | self.value = value 5 | self.next = next 6 | 7 | def __str__(self): 8 | return str(self.value) 9 | 10 | # Those are our objects or node 11 | mynode1 = Node("first") 12 | mynode2 = Node("Second") 13 | mynode3 = Node("third") 14 | 15 | # Now we can link them 16 | mynode1.next = mynode2 17 | mynode2.next = mynode3 18 | 19 | 20 | #Printing the nodes after the node defined her as cell 21 | #Iterate(mynode2) 22 | #Result: 23 | #Second 24 | #third 25 | def Iterate(cell): 26 | while (cell): 27 | print cell 28 | cell=cell.next 29 | 30 | #Finding Nodes 31 | #Cell: FindCell(Cell: top, Value: target) 32 | def FindCell(top,target): 33 | 34 | #While (top != null) 35 | while (top != None): 36 | #If (top.Value == target) Then Return top 37 | if (top.value == target): 38 | return top 39 | #top = top.Next 40 | top = top.next 41 | return None 42 | 43 | #print (FindCell(mynode2,"first")) 44 | 45 | #Find Cell Before 46 | #Cell: FindCellBefore(Cell: top, Value: target) 47 | def FindCellBefore(top, target): 48 | if(top == None): 49 | return none 50 | while(top.next != None): 51 | if(top.next.value == target): 52 | return top 53 | top = top.next 54 | return None 55 | #print FindCellBefore(mynode1, "first") 56 | 57 | #add a sentinel to your links 58 | sentinel = Node("") 59 | sentinel.next = mynode1 60 | ''' 61 | What is Sentinel? 62 | 63 | When we are looking for target value which is located in first node 64 | but we are looking at the target value's before value, it will throw an error. 65 | Sentinel prevents this situation to happen. Basically we are creating another 66 | object called sentinel before everthing, before actual linked list start. 67 | 68 | ''' 69 | #-------------------------------------------------------------------# 70 | #Adding cells at the beginning 71 | #AddAtBeginning(Cell: top, Cell: new_cell) 72 | def AddAtBeginning(top,new_cell): 73 | #new_cell.Next = top.Next 74 | new_cell.next = top.next 75 | #top.Next = new_cell 76 | top.next = new_cell 77 | #End AddAtBeginning 78 | 79 | new_one=Node("add me at the beginning") 80 | AddAtBeginning(sentinel,new_one) 81 | #Iterate(sentinel) #Beginning 82 | #-------------------------------------------------------------------# 83 | #Adding cells at the end 84 | #AddAtEnd(Cell: top, Cell: new_cell) 85 | def AddAtEnd(top,new_cell): 86 | #// Find the last cell. 87 | #While (top.Next != null) 88 | while(top.next != None): 89 | # top = top.Next 90 | top = top.next 91 | #// Add the new cell at the end. 92 | #top.Next = new_cell 93 | top.next = new_cell 94 | #new_cell.Next = null 95 | new_cell.next = None 96 | #End AddAtEnd 97 | 98 | new_one=Node("add me at the end") 99 | AddAtEnd(sentinel,new_one) 100 | 101 | #-------------------------------------------------------------------# 102 | #Inserting after other cells 103 | #InsertCell(Cell: after_me, Cell: new_cell) 104 | def InsertCell(after_me,new_cell): 105 | #new_cell.Next = after_me.Next 106 | new_cell.next = after_me.next 107 | #after_me.Next = new_cell 108 | after_me.next = new_cell 109 | #End InsertCell 110 | 111 | new_one=Node("add me after SECOND") 112 | InsertCell(mynode2,new_one) 113 | #Iterate(sentinel) 114 | 115 | #-------------------------------------------------------------------# 116 | 117 | #Delete after me 118 | #DeleteAfter(Cell: after_me) 119 | def DeleteAfter(after_me): 120 | #after_me.Next = after_me.Next.Next 121 | after_me.next =after_me.next.next 122 | #End DeleteAfter 123 | 124 | #DeleteAfter(mynode2) 125 | #Iterate(sentinel) 126 | #-------------------------------------------------------------------# 127 | 128 | 129 | #Destroy the List 130 | #Pseudocode: 131 | ''' 132 | DestroyList(Cell: top) 133 | While (top != null) 134 | // Save a pointer to the next cell. 135 | Cell: next_cell = top.Next 136 | // Free top. 137 | free(top) 138 | // Move to the next cell. 139 | top = next_cell 140 | End While 141 | End DestroyList 142 | ''' 143 | 144 | 145 | def DestroyList(top): 146 | while(top != None): 147 | # Save a pointer to the next cell 148 | next_cell = top.next 149 | 150 | #free(top) # In some languages you need to free the space 151 | # > but in python yo dont have to 152 | # Move to the next cell 153 | top = next_cell 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | -------------------------------------------------------------------------------- /List_of_primes_faster.py: -------------------------------------------------------------------------------- 1 | def primes(n): 2 | if n==2: 3 | return [2] 4 | elif n<2: 5 | return [] 6 | 7 | s=range(3,n+1,2) 8 | 9 | mroot = n ** 0.5 10 | 11 | half=(n+1)/2-1 12 | i=0 13 | m=3 14 | while m <= mroot: 15 | if s[i]: 16 | j=(m*m-3)/2 17 | s[j]=0 18 | while j 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /MergeSort_Algorithm1.py: -------------------------------------------------------------------------------- 1 | ''' Merge Sort ''' 2 | from heapq import merge 3 | 4 | def merge_sort(m): 5 | if len(m) <= 1: 6 | return m 7 | 8 | middle = len(m) // 2 9 | left = m[:middle] 10 | right = m[middle:] 11 | 12 | left = merge_sort(left) 13 | right = merge_sort(right) 14 | return list(merge(left, right)) 15 | -------------------------------------------------------------------------------- /MergeSort_Algorithm2.py: -------------------------------------------------------------------------------- 1 | ''' Merge Sort 2 ''' 2 | def merge(left, right): 3 | result = [] 4 | left_idx, right_idx = 0, 0 5 | while left_idx < len(left) and right_idx < len(right): 6 | # change the direction of this comparison to change the direction of the sort 7 | if left[left_idx] <= right[right_idx]: 8 | result.append(left[left_idx]) 9 | left_idx += 1 10 | else: 11 | result.append(right[right_idx]) 12 | right_idx += 1 13 | 14 | if left: 15 | result.extend(left[left_idx:]) 16 | if right: 17 | result.extend(right[right_idx:]) 18 | return result 19 | -------------------------------------------------------------------------------- /MinHash.py: -------------------------------------------------------------------------------- 1 | # Author: Enes Kemal Ergin 2 | # Date: 03/11/2017 3 | 4 | # This is the my understanding and implementation of MinHashing Algorithm 5 | # Sources that I've used to learn: 6 | # 1. http://mccormickml.com/2015/06/12/minhash-tutorial-with-python-code/ 7 | # 2. http://maciejkula.github.io/2015/02/01/minhash/ 8 | # 3. https://robertheaton.com/2014/05/02/jaccard-similarity-and-minhash-for-winners/ 9 | # 4. http://www.bogotobogo.com/Algorithms/minHash_Jaccard_Similarity_Locality_sensitive_hashing_LSH.php 10 | 11 | # Will work on more 12 | 13 | 14 | from random import randint, seed, choice, random 15 | import string 16 | import sys 17 | import itertools 18 | 19 | def generate_random_docs(n_docs, max_doc_length, n_similar_docs): 20 | for i in range(n_docs): 21 | if n_similar_docs > 0 and i % 10 == 0 and i > 0: 22 | permuted_doc = list(lastDoc) 23 | permuted_doc[randint(0,len(permuted_doc))] = choice('1234567890') 24 | n_similar_docs -= 1 25 | yield ''.join(permuted_doc) 26 | else: 27 | lastDoc = ''.join(choice('aaeioutgrb ') for _ in range(randint(int(max_doc_length*.75), max_doc_length))) 28 | yield lastDoc 29 | 30 | def generate_shingles(doc, shingle_size): 31 | shingles = set([]) 32 | for i in range(len(doc)-shingle_size+1): 33 | shingles.add(doc[i:i+shingle_size]) 34 | return shingles 35 | 36 | def get_minhash(shingles, n_hashes, random_strings): 37 | minhash_row = [] 38 | for i in range(n_hashes): 39 | minhash = sys.maxint 40 | for shingle in shingles: 41 | hash_candidate = abs(hash(shingle + random_strings[i])) 42 | if hash_candidate < minhash: 43 | minhash = hash_candidate 44 | minhash_row.append(minhash) 45 | return minhash_row 46 | 47 | def get_band_hashes(minhash_row, band_size): 48 | band_hashes = [] 49 | for i in range(len(minhash_row)): 50 | if i % band_size == 0: 51 | if i > 0: 52 | band_hashes.append(band_hash) 53 | band_hash = 0 54 | band_hash += hash(minhash_row[i]) 55 | return band_hashes 56 | 57 | def get_similar_docs(docs, n_hashes=400, band_size=7, shingle_size=3, collectIndexes=True): 58 | hash_bands = {} 59 | random_strings = [str(random()) for _ in range(n_hashes)] 60 | docNum = 0 61 | for doc in docs: 62 | shingles = generate_shingles(doc, shingle_size) 63 | minhash_row = get_minhash(shingles, n_hashes, random_strings) 64 | band_hashes = get_band_hashes(minhash_row, band_size) 65 | 66 | docMember = docNum if collectIndexes else doc 67 | for i in range(len(band_hashes)): 68 | if i not in hash_bands: 69 | hash_bands[i] = {} 70 | if band_hashes[i] not in hash_bands[i]: 71 | hash_bands[i][band_hashes[i]] = [docMember] 72 | else: 73 | hash_bands[i][band_hashes[i]].append(docMember) 74 | docNum += 1 75 | 76 | similar_docs = set() 77 | for i in hash_bands: 78 | for hash_num in hash_bands[i]: 79 | if len(hash_bands[i][hash_num]) > 1: 80 | for pair in itertools.combinations(hash_bands[i][hash_num], r=2): 81 | similar_docs.add(pair) 82 | 83 | return similar_docs 84 | 85 | if __name__ == '__main__': 86 | n_hashes = 200 87 | band_size = 7 88 | shingle_size = 3 89 | n_docs = 1000 90 | max_doc_length = 40 91 | n_similar_docs = 10 92 | seed(42) 93 | docs = generate_random_docs(n_docs, max_doc_length, n_similar_docs) 94 | 95 | similar_docs = get_similar_docs(docs, n_hashes, band_size, shingle_size, collectIndexes=False) 96 | 97 | print(similar_docs) 98 | r = float(n_hashes/band_size) 99 | similarity = (1/r)**(1/float(band_size)) 100 | print("similarity: %f" % similarity) 101 | print("# Similar Pairs: %d" % len(similar_docs)) 102 | 103 | if len(similar_docs) == n_similar_docs: 104 | print("Test Passed: All similar pairs found.") 105 | else: 106 | print("Test Failed.") 107 | -------------------------------------------------------------------------------- /Number Theory/ChineseRemTheorem.py: -------------------------------------------------------------------------------- 1 | # Chinese Remainder Theorem Implementation 2 | # Enes Kemal Ergin 3 | # 03/22/15 4 | 5 | def mul_inv(a, b): 6 | b0 = b 7 | x0, x1 = 0, 1 8 | if b == 1: return 1 9 | while a > 1: 10 | q = a / b 11 | a, b = b, a%b 12 | x0, x1 = x1 - q * x0, x0 13 | if x1 < 0: x1 += b0 14 | return x1 15 | 16 | def chinese_remainder(n, a, lena): 17 | p = i = prod = 1; sm = 0 18 | for i in range(lena): prod *= n[i] 19 | for i in range(lena): 20 | p = prod / n[i] 21 | sm += a[i] * mul_inv(p, n[i]) * p 22 | return sm % prod 23 | 24 | if __name__ == '__main__': 25 | n = [3, 5, 7] 26 | a = [2, 3, 2] 27 | print(chinese_remainder(n, a, len(n))) -------------------------------------------------------------------------------- /Number Theory/CongruenceFinder.py: -------------------------------------------------------------------------------- 1 | # Brute-force congruence Finder 2 | # Author: Enes Kemal Ergin 3 | """ 4 | ax = b(mod -mod-) 5 | a is a integer constant 6 | b is a integer remainder 7 | x is a result that we want to obtain 8 | -mod- is a integer which base we want to find x 9 | 10 | This is the least efficient method: 11 | """ 12 | # Type 1: ax = b type 13 | def congrFindV1(a, mod = 10, result = 0): 14 | p=[] 15 | for x in range(0,mod): 16 | if (a*x) % mod == result : 17 | p.append(x) 18 | return p 19 | 20 | 21 | 22 | import time # To check the execution time 23 | 24 | # Test Cases solved in Class 25 | start_time = time.time() # To check the execution time 26 | print(congrFindV1(18,22, 8)) 27 | print("1st Execution: %.5s miliseconds" % (time.time() - start_time))# To check the execution time 28 | 29 | start_time = time.time() 30 | print(congrFindV1(4,19, 3)) 31 | print("2nd Execution: %.5s miliseconds" % (time.time() - start_time))# To check the execution time 32 | 33 | start_time = time.time() # To check the execution time 34 | print(congrFindV1(6, 514, 15)) 35 | # No Result because divisibilty error. 36 | print("3rd Execution: %.5s miliseconds" % (time.time() - start_time))# To check the execution time 37 | -------------------------------------------------------------------------------- /Number Theory/HornerPolyEval.py: -------------------------------------------------------------------------------- 1 | ## Horner's Rule of Polynomial Evaluation 2 | # Enes Kemal Ergin 3 | # 03/26/15 4 | 5 | """ 6 | coefficients := [-19, 7, -4, 6] # list coefficients of all x^0..x^n in order 7 | when x = 3 8 | test HornerPolyEval() 9 | 10 | Suggested Types: for coefficients use list of integers 11 | 12 | """ 13 | def HornerPolyEval(list_coeffs, x): 14 | result = 0 15 | for i in reversed(list_coeffs): 16 | result = result * x + i 17 | return result 18 | 19 | # Test Case 1 20 | # HornerPolyEval((-19,7,-4,6), 3) -------------------------------------------------------------------------------- /Number Theory/IntegerSolutions.py: -------------------------------------------------------------------------------- 1 | # 2 | # Author: Enes Kemal Ergin 3 | 4 | """ 5 | Find positive integer solutions to the equation x^2 - 2y^2 = 1 6 | Parameters: 7 | n -> Find solutions until n 8 | """ 9 | 10 | def psearch(n): 11 | for x in range(0, n): 12 | for y in range(0, n): 13 | if x*x - 2*y*y == 1: 14 | print x, y 15 | 16 | 17 | # Tests 18 | psearch(1000) 19 | 20 | 21 | -------------------------------------------------------------------------------- /Number Theory/PPT_UnitCircle.py: -------------------------------------------------------------------------------- 1 | def rprime(x, y): 2 | for d in range(2, min(x, y) + 1): 3 | if x % d == 0 and y % d == 0: 4 | return False 5 | return True 6 | 7 | def PPT_UnitCircle(upper): 8 | for u in range(1, upper+1): 9 | for v in range(1, u): 10 | a = u**2 - v**2 11 | b = 2*u*v 12 | c = u**2 + v**2 13 | if (u + v) % 2 != 0 and rprime(u, v): 14 | print(a, b, c), 15 | 16 | PPT_UnitCircle(5) -------------------------------------------------------------------------------- /Number Theory/README.md: -------------------------------------------------------------------------------- 1 | # Number Theoratical Algorithms 2 | 3 | ## Chapters 4 | 5 | 1. What is Number Theory? 6 | 2. [Pythagorean Triples](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/pythagoreanTriples.py) 7 | 3. [Pythagorean Triples and Unit Circle](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/PPT_UnitCircle.py) 8 | 4. Sums and Higher Powers and Fermat's Last Theorem 9 | 5. Divisibility and the GCD 10 | - [Great Common Divisor](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/gcd.py) 11 | - [Least Common Multiplier](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/lcm.py) 12 | - [Least Common Multiplier for multiple inputs](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/lcmm.py) 13 | 6. Linear Equations and the GCD 14 | - [extendedGCD](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/extendedGCD.py) 15 | - [Printed Version of extendedGCD](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/extendedGCD_print.py) 16 | 7. Factorization and the Fundamental Theorem of Arithmetic 17 | 8. [Congruences](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/incongruentFinder.py) 18 | 9. [Congruences, Powers, and Fermat's Little Theorem]() 19 | 10. [Congruences, Powers, and Euler's Formula](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/eulerPhiFunction.py) 20 | 11. [Euler's Phi Function and the Chinese Remainder Theorem](https://github.com/eneskemalergin/Essential_Algorithms_Python/blob/master/Number%20Theory/ChineseRemTheorem.py) -------------------------------------------------------------------------------- /Number Theory/Series.py: -------------------------------------------------------------------------------- 1 | # Section 1 ~ Series 2 | 3 | # Question 1 4 | """ Find the sum of the series 1 + 1/2 + 1/3 + 1/4 + .... + 1/100 """ 5 | 6 | def Q1(upper = 100): 7 | sum = 0 8 | for i in range(1,upper+1): 9 | sum = sum + 1/i 10 | return(sum) 11 | # Question 2 12 | """ Find the sum 1 + 1/2^2 + 1/3^2 + .... + 1/100^2 """ 13 | 14 | def Q2(upper = 100): 15 | sum = 0 16 | for i in range(1, upper+1): 17 | sum += 1/(i**2) 18 | return(sum) 19 | # Question 3 20 | """ Find the sum 1 - 1/2 + 1/3 - 1/4 + .... + 1/99 - 1/100 """ 21 | 22 | def Q3(upper = 100): 23 | sum = 0 24 | k = 1 25 | while k <= 100: 26 | if k % 2 == 1: 27 | sum += 1/k 28 | else: 29 | sum -= 1/k 30 | k += 1 31 | return(sum) 32 | 33 | # Question 4 34 | """ Define a function factorial(n) that computes n! = 1.2.3...n""" 35 | def factorial(n): 36 | if n == 0: 37 | return 1 38 | elif n == 1: 39 | return 1 40 | else: 41 | return (n * factorial(n-1) ) 42 | 43 | # Question 5 44 | """ Define a binomial to compute binomial coefficients. """ 45 | 46 | def log_binomial(n,k): 47 | return (log_fac(n)-log_fac(k)-log_fac(n-k)) 48 | 49 | # Question 6 50 | """ How many points are there with integer coordinates that lie in the 51 | circle of radius 100? """ 52 | 53 | def L(radius): 54 | count = 0 55 | m = -radius 56 | while m <= r: 57 | n = -r 58 | while n <=r: 59 | if m*m + n*n <= r*r: 60 | count += 1 61 | n += 1 62 | m += 1 63 | return count 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Number Theory/TrialDivision.py: -------------------------------------------------------------------------------- 1 | # Trial Division 2 | # Author: Enes Kemal Ergin 3 | 4 | """ 5 | Factorizations slowest to fastest 6 | """ 7 | def factor1(n): 8 | d = 2 9 | while n>1: 10 | if n%d == 0: 11 | n = n/d 12 | print d, 13 | else: 14 | d += 1 15 | print 16 | return n 17 | 18 | # Tests 19 | factor1(1234) 20 | 21 | factor1(4321) -------------------------------------------------------------------------------- /Number Theory/eulerPhiFunction.py: -------------------------------------------------------------------------------- 1 | def GCD(a, b): 2 | while (b != 0): 3 | remainder = a % b 4 | a = b 5 | b = remainder 6 | return a 7 | 8 | def eulerPhiFun(m): 9 | M = [a for a in range(m+1) if 1 <= a <= m and GCD(a,m) == 1] 10 | print(M) 11 | print(len(M)) 12 | 13 | # eulerPhiFun(10) | 4 | ~ 0.0s 14 | # eulerPhiFun(100) | 40 | ~ 0.0s 15 | # eulerPhiFun(1000) | 400 | ~ 0.0s 16 | # eulerPhiFun(10000) | 4000 | ~ 0.1s 17 | # eulerPhiFun(100000) | 40000 | ~ 10.5s 18 | 19 | # Checks if Code is correct: 20 | # to find GCD of random number from result with m 21 | """ 22 | print(GCD(949, 1000)) 23 | print(GCD(351, 1000)) 24 | print(GCD(37, 1000)) 25 | print(GCD(13, 1000)) 26 | 27 | """ -------------------------------------------------------------------------------- /Number Theory/extendedGCD.py: -------------------------------------------------------------------------------- 1 | # Prints (gcd(), lastx, lasty) 2 | def extendedGCD(a, b): 3 | if a == 0: 4 | return (b, 0, 1) 5 | else: 6 | g, y, x = extendedGCD(b % a, a) 7 | return (g, x - (b // a) * y, y) # I didn't get it! 8 | 9 | """ Print type: (gcd(a,b), x, y) """ 10 | print(extendedGCD(78, 42)) 11 | 12 | 13 | -------------------------------------------------------------------------------- /Number Theory/extendedGCD_print.py: -------------------------------------------------------------------------------- 1 | def extendedGCD_print(a,b): 2 | origa = a 3 | origb = b 4 | 5 | x = 0 6 | lastx = 1 7 | y = 1 8 | lasty = 0 9 | 10 | while b != 0: 11 | q = a // b 12 | a, b = b, a % b 13 | 14 | full = "%d = (%d * %d + %d * %d) - %d * (%d * %d + %d * %d) " % ( b, origa, lastx, origb, lasty, q, origa, x, origb, y ) 15 | short = "%d = %d * %d + %d * %d" % ( b, origa, lastx - x * q, origb, lasty - y * q) 16 | print("%s\t%s\t%s\t%s" % (a, b, full, short)) 17 | 18 | x, lastx = (lastx - q * x, x) 19 | y, lasty = (lasty - q * y, y) 20 | 21 | return (lastx, lasty) 22 | 23 | print(extendedGCD_print(78, 42)) -------------------------------------------------------------------------------- /Number Theory/gcd.py: -------------------------------------------------------------------------------- 1 | # Great Common Divisor gcd(a,b) 2 | # Author: Enes Kemal Ergin 3 | 4 | """ Following method finds the great common divisor 5 | for given numbers a and b """ 6 | def gcd(a,b): 7 | while(b != 0): 8 | remainder = a % b 9 | a = b 10 | b = remainder 11 | return a 12 | 13 | # Test Cases from Class 14 | 15 | # To test them you need to extract test cases from comment. 16 | """ 17 | print gcd(60, 144) 18 | print gcd(144, 60) 19 | print gcd(335, 780) 20 | print gcd(1160718174, 316258250) 21 | 22 | # Test Cases from Book 23 | print gcd(12345,67890) 24 | print gcd(54321,9876) 25 | 26 | """ -------------------------------------------------------------------------------- /Number Theory/incongruentFinder.py: -------------------------------------------------------------------------------- 1 | # Finding all incongruences for linear equations 2 | 3 | def extendedGCD(a, b): 4 | if a == 0: 5 | return (b, 0, 1) 6 | else: 7 | g, y, x = extendedGCD(b % a, a) 8 | return (g, x - (b // a) * y, y) 9 | 10 | """ 11 | From 6x is equivalent to 15 in mod 514 12 | a = 6 13 | mod = 514 14 | result = 15 15 | """ 16 | 17 | def incongrFind(a, mod, result): 18 | func = extendedGCD(a, mod) 19 | g = func[0] 20 | x = func[1] 21 | y = func[2] 22 | list_ = [] 23 | 24 | #if gcd(a, mod) does not divide result 25 | if result % g != 0: 26 | # There is no solution 27 | return list_ 28 | 29 | x0 = x * (result/g) 30 | while g > 0: 31 | list_.append(x0) 32 | x0 = x0 + (g * ( mod / g)) 33 | g -= 1 34 | 35 | return list_ 36 | 37 | # Test Cases 38 | print(incongrFind(42, 78, 12)) 39 | print(incongrFind(943, 2576, 381)) 40 | print(incongrFind(51, 1008, 177)) 41 | print(incongrFind(97, 53460, 1)) 42 | print(incongrFind(4, 19, 3)) -------------------------------------------------------------------------------- /Number Theory/largestPrime.py: -------------------------------------------------------------------------------- 1 | # Author: Enes Kemal Ergin 2 | # 03/27/15 3 | # This is the fastest implementation so far 4 | def largest_prime(number): 5 | largest_prime = 0 6 | counter = 2 7 | while counter * counter <= number: 8 | if number % counter == 0: 9 | number = number / counter 10 | largest_prime = counter 11 | else: 12 | counter += 1 13 | if number > largest_prime: 14 | largest_prime = number 15 | print largest_prime 16 | 17 | largest_prime(52633) -------------------------------------------------------------------------------- /Number Theory/lcm.py: -------------------------------------------------------------------------------- 1 | # Least Common Multiplier 2 | # Author: Enes Kemal Ergin 3 | from gcd import gcd 4 | def lcm(a,b): 5 | return a * b / gcd(a,b) 6 | 7 | # Test Cases 8 | """ 9 | print lcm(3,7) 10 | print lcm(12,66) 11 | print lcm(8,12) 12 | print lcm(20,30) 13 | print lcm(51,68) 14 | print lcm(23,18) 15 | """ -------------------------------------------------------------------------------- /Number Theory/lcmm.py: -------------------------------------------------------------------------------- 1 | # Least Common Multiplier for multiple inputs 2 | # Author: Enes Kemal Ergin 3 | 4 | from lcm import lcm 5 | def lcmm(*args): 6 | return reduce(lcm, args) 7 | 8 | 9 | print lcmm(12,3,6,4) -------------------------------------------------------------------------------- /Number Theory/pythagoreanTriples.py: -------------------------------------------------------------------------------- 1 | # Author: Enes Kemal Ergin 2 | #03/26/15 3 | 4 | """ 5 | Primordial Algortihm to find Pythagorean Triples using 6 | 7 | a^2 + b^2 = c^2 equations to find PT's 8 | 9 | PT() function requires 1 parameter n which is the upper limit of 10 | c in PT. When looping reach that point looping stops. 11 | """ 12 | def PT(n): 13 | counter = 1 14 | for a in range(1,n): 15 | for b in range(a, n): 16 | for c in range(b,n): 17 | if a**2 + b**2 == c**2: 18 | print(str(counter) + ')', a, b, c) 19 | counter += 1 20 | return n 21 | # Test Case 22 | # print(PT(100)) 23 | 24 | 25 | """ 26 | This is more advanced method of finding Primitive Pythagorean Triples 27 | """ 28 | from math import sqrt 29 | def PPT_faster(n): 30 | a, b, c = 1, 3, 0 31 | while c < n: 32 | a_ = (a * b) + a 33 | c = sqrt(a_**2 + b**2) 34 | if c == int(c): 35 | yield b, a_, int(c) 36 | a += 1 37 | b += 2 38 | 39 | # Test Case 40 | #for pt in pythagorean_triples(1000): 41 | # print(pt) 42 | 43 | 44 | # Finishs up to 1000 in ~0.8 seconds. 45 | def PPT_fastest(n=1000): 46 | for a in xrange(1, n): 47 | a2= a*a 48 | for b in xrange(a+1, n): 49 | c2= a2 + b*b 50 | cs= int(c2**.5) 51 | if cs*cs == c2: 52 | yield a, b, cs 53 | 54 | # Test Case 55 | print list(PPT_fastest()) -------------------------------------------------------------------------------- /One_Dimensional_lists.py: -------------------------------------------------------------------------------- 1 | # One Dimensional Arrays(Lists in Python): 2 | ''' In Python there is no specific data structures called arrays ''' 3 | ''' We are using lists instead of arrays ''' 4 | 5 | 6 | ''' Finding Items in List ''' 7 | def IndexOf(list, target): 8 | for i in range(len(list)): 9 | if list[i] == target: 10 | return i 11 | # Returns False means target not in the list 12 | return False 13 | # O(N) Efficiency 14 | 15 | ''' Finding Minimum value in the list ''' 16 | def FindMin(list): 17 | minimum = list[0] 18 | for i in list: 19 | if list[i] < minimum: 20 | minimum = list[i] 21 | 22 | return minimum 23 | 24 | ''' Finding Maximum value in the list ''' 25 | 26 | def FindMax(list): 27 | maximum = list[0] 28 | for i in list: 29 | if list[i] > maximum: 30 | maximum = list[i] 31 | 32 | return maximum 33 | 34 | ''' Finding Average of the list ''' 35 | def FindAverage(list): 36 | total = 0 37 | for i in list: 38 | total += list[i] 39 | 40 | return total / len(list) 41 | 42 | 43 | ''' Finding the median of the List ''' 44 | def FindMedian(list): 45 | for i in list: 46 | # Finding the number of values greater than and less than array[i] 47 | num_smaller = 0 48 | num_greater = 0 49 | 50 | for j in list: 51 | if(list[j] < list[i]): 52 | num_smaller += 1 53 | elif(list[j] > list[i]): 54 | num_greater += 1 55 | else: 56 | pass 57 | 58 | if num_smaller == num_greater: 59 | return list[i] 60 | # O(NxN) Efficiency 61 | 62 | 63 | ''' Inserting an element to the end of the list ''' 64 | def InsertToEnd(list): 65 | # Taking value from the user 66 | value = raw_input() 67 | # Appending to the end of the list 68 | list.append(value) 69 | 70 | ''' Copying the list to another using append: ''' 71 | 72 | ar = [] # Make an empty list 73 | for i in list: 74 | ar.append(i) 75 | 76 | print ar 77 | 78 | return None 79 | 80 | 81 | 82 | def InsertToIndex(list): 83 | # Taking value from the user 84 | value = raw_input() 85 | # Ask user for index 86 | index = raw_input() 87 | # Add value to specific index 88 | list.insert(index, value) 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /Pin Problem 1.py: -------------------------------------------------------------------------------- 1 | # Pin Problem 1 2 | 3 | ''' 4 | * positive number (integer, float point number) < n 5 | * an its divisible by m other numbers 6 | * List of m numbers 7 | 8 | 9 | input 10 | - t number of test cases. 11 | - 12 | ''' 13 | -------------------------------------------------------------------------------- /Push_Pop_Array_stack.py: -------------------------------------------------------------------------------- 1 | # Pushing and Popping an item for Array stack: 2 | 3 | ''' Those algorithms work only with already implemented Array structure ''' 4 | 5 | def Push(stack_values, next_index, new_value): 6 | # Make sure there's room to add an item 7 | 8 | if next_index == len(stack_values): 9 | return "Not Enough Space" 10 | 11 | # Add the new item 12 | stack_values(next_index) = new_value 13 | 14 | # Increment next_index 15 | next_index = next_index + 1 16 | 17 | def Pop(stack_values, next_index): 18 | # Make sure there is na item to pop 19 | if next_index == 0 : 20 | return "Already Empty" 21 | 22 | # Decrement next_index 23 | next_index = next_index - 1 24 | 25 | # return the top value 26 | return stack_values(next_index) 27 | -------------------------------------------------------------------------------- /Push_Pop_Array_two_stack.py: -------------------------------------------------------------------------------- 1 | # Showing pushing and popping items with two stacks contained in a single array 2 | 3 | stack_values = [input()] 4 | 5 | def Initialize(): 6 | next_index1 = 0 7 | next_index2 = len(stack_values) - 1 8 | 9 | #End 10 | 11 | # Add an item to the top stack 12 | def Push1(new_value): 13 | # Make sure there's room to add an item 14 | if(next_index1 > next_index2): 15 | return "Not Enough Room" 16 | 17 | # Add the new item, 18 | stack_values[next_index1] = new_value 19 | 20 | # Increment Next_index1 21 | next_index1 = next_index + 1 22 | 23 | # Add an item to the bottom stack 24 | def Push2(new_value): 25 | # Make sure there's room to add an item. 26 | if next_index1 > next_index2: 27 | return "Not Enough Room" 28 | 29 | # Add the new item 30 | stack_values[next_index2] = new_value 31 | 32 | # Decrement next_index2 33 | next_index2 = next_index2 - 1 34 | 35 | # Remove an item from the top stack 36 | def Pop1(): 37 | # Make sure there's room to add an item 38 | if next_index1 == 0: 39 | return "Already Empty" 40 | 41 | # Decrement Next_index1 42 | next_index1 = next_index1 - 1 43 | 44 | # Return the top value 45 | return stack_values[next_index1] 46 | 47 | 48 | # Remove an item form the bottom stack 49 | def Pop2(): 50 | # Make sure there is an item to pop 51 | if next_index2 == len(stack_values) - 1: 52 | return "Already Empty" 53 | 54 | # Increment next_index2 55 | next_index2 = next_index2 + 1 56 | 57 | # Return the top value 58 | return stack_values[next_index2] 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /Push_Pop_LLstack.py: -------------------------------------------------------------------------------- 1 | # Pushing and Popping an item for linked list stack: 2 | 3 | ''' Those algorithms are working with already implemented linked list ''' 4 | def Push(sentinel, new_value): 5 | # Make a new cell to hold the new value 6 | new_cell = New_cell 7 | new_cell.value = new_value 8 | 9 | # Add the new cell to the linked list 10 | new_cell.next = sentinel.next 11 | sentinel.next = new_cell 12 | 13 | def Pop(sentinel): 14 | if sentine.next == None: 15 | return "Already Empty" 16 | 17 | # Get the top cell's value 18 | result = sentinel.next.value 19 | 20 | # Remove the top cell from the linked list 21 | sentinel.next = sentinel.next.next 22 | 23 | return result 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /QuickSort_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Quick Sort ''' 2 | def quickSort(arr): 3 | less = [] 4 | pivotList = [] 5 | more = [] 6 | if len(arr) <= 1: 7 | return arr 8 | else: 9 | pivot = arr[0] 10 | for i in arr: 11 | if i < pivot: 12 | less.append(i) 13 | elif i > pivot: 14 | more.append(i) 15 | else: 16 | pivotList.append(i) 17 | less = quickSort(less) 18 | more = quickSort(more) 19 | return less + pivotList + more 20 | 21 | # quickSort([4, 65, 2, -31, 0, 99, 83, 782, 1]) 22 | #[-31, 0, 1, 2, 4, 65, 83, 99, 782] 23 | 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Essential_Algorithms_Python 2 | =========================== 3 | 4 | I started to gather implementations of some selected algorithms inside the Essential Algorithms: A Practical Approach to Computer Algorithms by Rod Stephens. 5 | 6 | Then I implement more algorithms from different sources. In my last project I am gathering Number Theoratical algorithms inside the [NumberTheory](https://github.com/eneskemalergin/Essential_Algorithms_Python/tree/master/Number%20Theory) 7 | 8 | There is a numerical integration sample code in python showed in IPython. You can reach it from: [Numerical Integration](http://nbviewer.ipython.org/github/eneskemalergin/Essential_Algorithms_Python/blob/master/numInt.ipynb) 9 | 10 | > If you copy and paste the codes here, you will most probably get an error. Most of the codes here works with additional codes and data structure. In this repo, I tried to gather the types and little hints about them 11 | -------------------------------------------------------------------------------- /RandomizingArrays.py: -------------------------------------------------------------------------------- 1 | # Randomizing Arrays 2 | import random 3 | 4 | def RandomizeArray(myList): # Needs to take list 5 | max_i = myList[len(myList) - 1] 6 | print(myList) 7 | print(max_i) 8 | print(len(myList)) 9 | i = 0 10 | for i in range(len(myList)): 11 | j = random.randint(i,(len(myList) - 1)) 12 | temp = myList[i] 13 | myList[i] = myList[j] 14 | myList[j] = temp 15 | return myList 16 | # It is working 17 | -------------------------------------------------------------------------------- /Reverse_Array_Stack.py: -------------------------------------------------------------------------------- 1 | # Reversing an Array using stack structure 2 | 3 | def ReverseArray(values): 4 | # Push the values form the array onto the stack 5 | for i in values: 6 | stack.Push(values[i]) 7 | 8 | 9 | # Pop the items off the stack into the array 10 | for i in values: 11 | values[i] = stack.Pop() 12 | 13 | 14 | -------------------------------------------------------------------------------- /RhoIntFactorization.py: -------------------------------------------------------------------------------- 1 | # Integer Factorization Algorithm 2 | # Enes Lemal Ergin 3 | # 03/22/15 4 | 5 | """ Pollard Rho is an integer factorization algorithm, 6 | which is quite fast for large numbers. It is based on Floyd’s 7 | cycle-finding algorithm and on the observation that two numbers 8 | x and y are congruent modulo p with probability 0.5 after 1.177\sqrt{p} 9 | numbers have been randomly chosen. 10 | """ 11 | 12 | # Legacy Style 13 | def RhoIntegerFactorization(N): 14 | if N%2==0: 15 | return 2 16 | x = random.randint(1, N-1) 17 | y = x 18 | c = random.randint(1, N-1) 19 | g = 1 20 | while g==1: 21 | x = ((x*x)%N+c)%N 22 | y = ((y*y)%N+c)%N 23 | y = ((y*y)%N+c)%N 24 | g = gcd(abs(x-y),N) 25 | return g 26 | 27 | 28 | # Richard Brent improved Rho's Algorithm: 29 | # This is more efficient than the Rho's Algorithm 30 | def BrentIntegerFactorization(N): 31 | if N%2==0: 32 | return 2 33 | y,c,m = random.randint(1, N-1),random.randint(1, N-1),random.randint(1, N-1) 34 | g,r,q = 1,1,1 35 | while g==1: 36 | x = y 37 | for i in range(r): 38 | y = ((y*y)%N+c)%N 39 | k = 0 40 | while (k1: 53 | break 54 | 55 | return g -------------------------------------------------------------------------------- /Sample Challange.py: -------------------------------------------------------------------------------- 1 | # Sample Challenge 2 | # This is a simple challenge to get things started. Given a sorted array (ar) and a number (V), can you print the index location of V in the array? 3 | # 4 | # {The next section describes the input format. You can often skip it, if you are using included methods. } 5 | # 6 | # Input Format 7 | # There will be three lines of input: 8 | # 9 | # V - the value that has to be searched. 10 | # n - the size of the array. 11 | # ar - n numbers that make up the array. 12 | # 13 | # Output Format 14 | # Output the index of V in the array. 15 | # 16 | # {The next section describes the constraints and ranges of the input. You should check this section to know the range of the input. } 17 | 18 | V = eval(input()) 19 | n = eval(input()) 20 | i = 0 21 | ar = [] 22 | 23 | while(len(ar) != n): 24 | temp = eval(input("add value in list")) 25 | ar.append(temp) 26 | print(ar) 27 | 28 | for i in range(len(ar) - 1) : 29 | if ar[i] == V: 30 | print(ar.index(V)) 31 | 32 | 33 | -------------------------------------------------------------------------------- /SelectionSort_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Selection Sort ''' 2 | def selectionSort(seq): 3 | n = len(seq) 4 | for i in range(n-1): 5 | # Assume the ith element is the smallest 6 | smallNdx = i 7 | # Determine if any other element contains smaller value 8 | for j in range(i + 1, n): 9 | if seq[j] < seq[smallNdx]: 10 | smallNdx = j 11 | 12 | # Swap the ith value and smallNdx value if the smallest value is 13 | # not already i ints proper position. 14 | if smallNdx != i: 15 | temp = seq[i] 16 | seq[i] = seq[smallNdx] 17 | seq[smallNdx] = temp 18 | print seq 19 | return seq 20 | 21 | selectionSort([12, 5, 13, 8, 9, 65]) 22 | -------------------------------------------------------------------------------- /Stack_Selectionsort.py: -------------------------------------------------------------------------------- 1 | # Stack Selectionsort # 2 | 3 | ''' Sort the items in the stack ''' 4 | 5 | def StackSelectionsort(items): 6 | # Make the temporary stack 7 | temp_stack = New Stack 8 | 9 | num_items = len(Stack) 10 | for i in range(num_items): 11 | # Position the next item 12 | # Find the item that belongs in sorted position i 13 | 14 | '''Move the items that have not yet been sorted to temp_stack, 15 | keeping track of the largest. Store the largest item in variable 16 | largest_item. 17 | At this point there are (num_items - i - 1) unsorted items.''' 18 | 19 | '''Add largest_item to the original stack 20 | at the end of the previously sorted items.''' 21 | 22 | '''Move the unsorted items back from temp_stack to the 23 | original stack, skipping largest_item when you find it''' 24 | 25 | # End 26 | 27 | -------------------------------------------------------------------------------- /Stack_insertionsort.py: -------------------------------------------------------------------------------- 1 | # Stack Insertionsort # 2 | 3 | ''' Sort the items in the stack ''' 4 | ''' For running this code we need stack data structure already implemented ''' 5 | 6 | # items and temp_stack are stack data type. 7 | def StackInsertionsor(items): 8 | temp_stack = New Stack 9 | 10 | num_items = len(items) 11 | for i in range(num_items): 12 | # Position the next item 13 | # Pull off the first item 14 | next_item = items.Pop() 15 | 16 | # Implement following descriptions(guidance) 17 | ''' Move the items that have not yet been sorted to temp_stack. 18 | At this point there are (num_items - i - 1) unsorted items.> 19 | ''' 20 | ''' 21 | Move sorted items to the second stack until 22 | you find out where next_item belongs. 23 | ''' 24 | ''' Add next_item at this position.''' 25 | ''' ''' 26 | 27 | # End 28 | -------------------------------------------------------------------------------- /Turn_array_into_heap.py: -------------------------------------------------------------------------------- 1 | ''' Algorithm for turning array into a heap ''' 2 | def MakeHeap(array): 3 | # Add each item to the heap one at a time 4 | for i in range(len(array) - 1): 5 | # Start ar the new item, and work up to the root. 6 | index = i 7 | while index != 0: 8 | # Find the parent's index 9 | parent = (index - 1) / 2 10 | 11 | # if child <= parent, we are done, so 12 | # break out of the while loop 13 | if array[index] = array[parent]: 14 | break 15 | 16 | # Swap the parent and child 17 | temp = array[index] 18 | array[index] = array[parent] 19 | array[parent] = temp 20 | 21 | # move to the parent 22 | index = parent 23 | -------------------------------------------------------------------------------- /algorithmAnalysis.py: -------------------------------------------------------------------------------- 1 | """ 2 | alganal.py 3 | Description: 4 | A utility program to plot algorithmic time complexity of a function. 5 | Author: Mahesh Venkitachalam 6 | Website: electronut.in 7 | """ 8 | 9 | from matplotlib import pyplot 10 | import numpy as np 11 | import timeit 12 | from functools import partial 13 | import random 14 | 15 | def fconst(N): 16 | """ 17 | O(1) function 18 | """ 19 | x = 1 20 | 21 | def flinear(N): 22 | """ 23 | O(n) function 24 | """ 25 | x = [i for i in range(N)] 26 | 27 | def fsquare(N): 28 | """ 29 | O(n^2) function 30 | """ 31 | for i in range(N): 32 | for j in range(N): 33 | x = i*j 34 | 35 | def fshuffle(N): 36 | # O(N) 37 | random.shuffle(list(range(N))) 38 | 39 | def fsort(N): 40 | x = list(range(N)) 41 | random.shuffle(x) 42 | x.sort() 43 | 44 | def plotTC(fn, nMin, nMax, nInc, nTests): 45 | """ 46 | Run timer and plot time complexity 47 | """ 48 | x = [] 49 | y = [] 50 | for i in range(nMin, nMax, nInc): 51 | N = i 52 | testNTimer = timeit.Timer(partial(fn, N)) 53 | t = testNTimer.timeit(number=nTests) 54 | x.append(i) 55 | y.append(t) 56 | p1 = pyplot.plot(x, y, 'o') 57 | #pyplot.legend([p1,], [fn.__name__, ]) 58 | 59 | # main() function 60 | def main(): 61 | print('Analyzing Algorithms...') 62 | 63 | plotTC(fconst, 10, 1000, 10, 10) 64 | plotTC(flinear, 10, 1000, 10, 10) 65 | plotTC(fsquare, 10, 1000, 10, 10) 66 | #plotTC(fshuffle, 10, 1000, 1000, 10) 67 | plotTC(fsort, 10, 1000, 10, 10) 68 | 69 | # enable this in case you want to set y axis limits 70 | #pyplot.ylim((-0.1, 0.5)) 71 | 72 | # show plot 73 | pyplot.show() 74 | 75 | # call main 76 | if __name__ == '__main__': 77 | main() 78 | -------------------------------------------------------------------------------- /binaryConvertion.py: -------------------------------------------------------------------------------- 1 | # Binary 2 | def toBinary( num ): 3 | bits = [] 4 | negative = num < 0 5 | n = abs( num ) 6 | while not bits or n: 7 | n, bit = divmod(n,2) 8 | bits.append( str(bit) ) 9 | 10 | bits.reverse() 11 | binary = "".join( bits ) 12 | if negative: 13 | return( twoscomplement( binary ) ) 14 | else: 15 | return( binary ) 16 | def conversion(n): 17 | b = '' 18 | while n > 0: 19 | r = n%2 20 | n = n/2 21 | r = str(r) 22 | b = r+b 23 | return b 24 | def positive(n,bits,count): 25 | append_zeros = bits - count 26 | if append_zeros > 0: 27 | return "0" + (append_zeros-1)*"0" + conversion(n) 28 | 29 | def negative(n,bits,count,new_count): 30 | n = abs(n) 31 | append_zeros = bits - count 32 | while new_count > bits and new_count < bits-count: 33 | append_zeros = append_zeros - 2 34 | continue 35 | if append_zeros > 0: 36 | return "1" + (append_zeros-6)*"0" + conversion(n) 37 | 38 | def signed_mag(): 39 | print ("") 40 | print ("--------------------") 41 | print ("Signed Binary") 42 | print ("--------------------") 43 | print ("") 44 | n = int(raw_input("Please enter a signed integer: ")) 45 | bits = int(raw_input("Please enter the number of bits: ")) 46 | count = conversion(n).count("0") + conversion(n).count("1") 47 | new_count = 0 48 | new_count = negative(n,bits,count,new_count).count("0") \ 49 | + negative(n,bits,count,new_count).count("1") 50 | if bits - 1 < count: 51 | print ("Out of range.") 52 | else: 53 | if n < 0: 54 | print (n,"is encoded as", negative(n,bits,count,new_count), \ 55 | "in Signed Binary.") 56 | elif n > 0: 57 | print (n,"is encoded as", positive(n,bits,count), \ 58 | "in Signed Binary.") 59 | else: 60 | return None 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /bubbleSort_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' BubbleSort Algorithm''' 2 | def bubbleSort(seq): 3 | not_sorted = True 4 | n = len(seq) 5 | print "At the beginning: " 6 | print seq 7 | while not_sorted: 8 | # If following statements fail next statement will stop the loop 9 | not_sorted = False 10 | 11 | for i in range(n-1): 12 | if seq[i] <= seq[i+1]: 13 | continue; 14 | else: 15 | temp = seq[i] 16 | seq[i] = seq[i+1] 17 | seq[i+1] = temp 18 | 19 | not_sorted = True 20 | print seq 21 | return seq 22 | bubbleSort([12, 5, 13, 8, 9, 65]) 23 | -------------------------------------------------------------------------------- /circular_array_queue.py: -------------------------------------------------------------------------------- 1 | ''' implementation of a queue using circular array ''' 2 | from array import Array 3 | class CAQueue: 4 | # Creates and empty queue 5 | def __init__(self, maxSize): 6 | self._count = 0 7 | self._front = 0 8 | self._back = maxsize - 1 9 | self._qArray = Array(maxSize) 10 | 11 | def isEmpty(self): 12 | return self._count == 0 13 | 14 | def isFull(self): 15 | return self._count == len(self._qArray) 16 | 17 | def __len__(self): 18 | return self._count 19 | 20 | def enqueue(self, item): 21 | assert not self.isFull(), "Cannot enqueue to a full queue." 22 | maxSize = len(self._qArray) 23 | self._back = (self._back + 1) % maxSize 24 | self.+qArray[self._back] = item 25 | self._count += 1 26 | 27 | def dequeue(self): 28 | assert not self.isEmpty(), "Cannot dequeue from an empty queue." 29 | item = self._qArray[self._front] 30 | maxSize = len(self._qArray) 31 | self._front = (self._front + 1) % maxSize 32 | self._count -= 1 33 | return item 34 | -------------------------------------------------------------------------------- /element_remover.py: -------------------------------------------------------------------------------- 1 | def remove_threshold(arr, threshold): 2 | """Function to remove element from the list if the distance 3 | between them is smaller than threshold""" 4 | rem_list = [] 5 | for i in range(1,len(arr)): 6 | dist = arr[i] - arr[i-1] 7 | if dist <= threshold: 8 | rem_list.append(arr[i]) 9 | return [i for i in list(arr) if i not in rem_list] 10 | -------------------------------------------------------------------------------- /example4.py: -------------------------------------------------------------------------------- 1 | def func (n): 2 | result = (n*n*n/75)-(n*n/4)+n+10 3 | return result 4 | 5 | def func2(k): 6 | result = k/2 + 8 7 | return result 8 | 9 | 10 | -------------------------------------------------------------------------------- /extra_stack_example.py: -------------------------------------------------------------------------------- 1 | ''' Implementing Stack ''' 2 | 3 | # Stack can be implemented in several ways, most common ones are using 4 | # Python lists or linked list structure 5 | 6 | ''' Using Python List ''' 7 | # The easiest way to implement. 8 | class Stack: 9 | # Create an empty stack 10 | def __init__(self): 11 | self._theItems = list() 12 | 13 | # Returns True if the stack is empty 14 | def isEmpty(self): 15 | return len(self) == 0 16 | 17 | # Returns the number of items in the stack 18 | def __len__(self): 19 | return len(self._theItems) 20 | 21 | # Returns the top item on the stack without removing it 22 | def peek(self): 23 | assert not self.isEmpty(), "Cannot peek at an empty stack" 24 | return self._theItems[-1] 25 | 26 | # Removes and returns the top item on the stack 27 | def pop(self): 28 | assert not self._isEmpty(), "Cannot pop from an empty stack" 29 | return self._theItems.pop() 30 | 31 | # Push an item onto the top of the stack 32 | def push(self, item): 33 | self._theItems.append(item) 34 | 35 | # To call this and using: 36 | # objectName = Stack() 37 | # objectName.methodNameInsindeTheClass(ParameterValueIfAvailable) 38 | -------------------------------------------------------------------------------- /first_n_primes.py: -------------------------------------------------------------------------------- 1 | # To obtain first n prime numbers... 2 | # Very unusually way of doing it... 3 | import re, sys 4 | 5 | 6 | def isPrime(n): 7 | # see http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/ 8 | return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None 9 | 10 | 11 | N = int(sys.argv[1]) # number of primes wanted (from command-line) 12 | M = 100 # upper-bound of search space 13 | l = list() # result list 14 | 15 | while len(l) < N: 16 | l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l 17 | M += 100 # increment upper-bound 18 | 19 | print l[:N-1] # print result list limited to N elements -------------------------------------------------------------------------------- /hashMap.py: -------------------------------------------------------------------------------- 1 | ''' Implementation of the Map ADT using closed hashing and a probe with double hashing ''' 2 | from arrays import Array 3 | class HashMap: 4 | # Define constants to represent the status of each table entry. 5 | UNUSED = None 6 | EMPTY = _MapEntry(None, None) 7 | 8 | # Creates an empty map instance. 9 | def __init__(self): 10 | self._table = Array(7) 11 | self._count = 0 12 | self._maxCount = len(self._table) - len(self._table) // 3 13 | 14 | # Returns the number of entries in the map. 15 | def __len__(self): 16 | return self._count 17 | 18 | # Determines if the map contains the given key. 19 | def __contains__(self, key): 20 | slot = self._findSlot(key, False) 21 | return slot is not None 22 | 23 | # Adds a new entry to the map if the key does not exist. Otherwise, the 24 | # new value replaces the current value associated with the key. 25 | def add(self, key, value): 26 | if key in self: 27 | slot = self._findSlot(key, False) 28 | self._table[slot].value = value 29 | return False 30 | else: 31 | slot = self._findSlot(key, True) 32 | self._table[slot] = _MapEntry(key, value) 33 | self._count += 1 34 | if self._count == self._maxCount: 35 | self._rehash() 36 | return False 37 | 38 | # Return the value associated with the key. 39 | def valueOf(self, key): 40 | slot = self._findSlot(key, False) 41 | assert slot is not None, "Invalid map key." 42 | return self._table[slot].value 43 | 44 | # Removes the entry associated with the key 45 | def remove(self, key): 46 | 47 | # Returns and iterator for traversing the keys in the map. 48 | def __iter__(self): 49 | 50 | 51 | # Finds the slot containing the key or where the key can be added. 52 | # forInsert indicates if the search is for an insertion, which locates 53 | # the slot into which the new key can be added 54 | def _findSlot(self, key, forInsert): 55 | # Compute the home slot and the step size. 56 | slot = self._hash1(key) 57 | step = self._hash2(key) 58 | 59 | # Probe for the key 60 | M = len(self._table) 61 | while self._table[slot] is not UNUSED: 62 | if forInsert and \ 63 | (self._table[slot] is UNUSED or self._table[slot] is EMPTY): 64 | return slot 65 | elif not forInsert and \ 66 | (self._table[slot] is not EMPTY and self._table[slot].key == key): 67 | return slot 68 | else: 69 | slot = (slot + step) % M 70 | 71 | # Rebuilds the hash table 72 | def _rehash(self): 73 | # Create a new larger table. 74 | origTable = self._table 75 | newSize = len(self._table) * 2 + 1 76 | self._table = Array(newSize) 77 | 78 | # Modify the size attributes. 79 | self._count = 0 80 | self._maxCount = newSize - newSize // 3 81 | 82 | # Add the keys from the original array to the new table. 83 | for entry in origTable: 84 | if entry is not UNUSED and entry is not EMPTY: 85 | slot =self._findSlot(key, True) 86 | self._table[slot] = entry 87 | self._count += 1 88 | 89 | # The main hash fucntion for mapping keys to table etries. 90 | def _hash1(self, key): 91 | return abs(hash(key)) % len(self._table) 92 | 93 | # The second hash function used with double hashing probes 94 | def _hash2(self, key): 95 | return 1 + abs(hash(key)) % (len(self._table) - 2) 96 | 97 | # Storage class for holding the key/value pairs. 98 | class _MapEntry: 99 | def __init__(self, key, value): 100 | self.key = key 101 | self.value = value 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /heap_sort.py: -------------------------------------------------------------------------------- 1 | ''' Heap Sort ''' 2 | def siftdown(lst, start, end): 3 | root = start 4 | while True: 5 | child = root * 2 + 1 6 | if child > end: break 7 | if child + 1 <= end and lst[child] < lst[child + 1]: 8 | child += 1 9 | if lst[root] < lst[child]: 10 | lst[root], lst[child] = lst[child], lst[root] 11 | root = child 12 | else: 13 | break 14 | def heapsort(lst): 15 | ''' Heapsort. Note: this function sorts in-place (it mutates the list). ''' 16 | 17 | # in pseudo-code, heapify only called once, so inline it here 18 | for start in range((len(lst)-2)/2, -1, -1): 19 | siftdown(lst, start, len(lst)-1) 20 | 21 | for end in range(len(lst)-1, 0, -1): 22 | lst[end], lst[0] = lst[0], lst[end] 23 | siftdown(lst, 0, end - 1) 24 | return lst 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /implementing_queue_using_lists.py: -------------------------------------------------------------------------------- 1 | ''' Implementing a Queue using Python List ''' 2 | class Queue: 3 | #Creates an empty queue 4 | def __init__(self): 5 | self._qlist = list() 6 | 7 | # Returns True if the queue is empty 8 | def isEmpty(self): 9 | return len(self) == 0 10 | 11 | # Returns the number of items in the queue 12 | def __len__(self): 13 | return len(self._qlist) 14 | 15 | # Adds the given item to the queue 16 | def enqueue(self, item): 17 | self._qlist.append(item) 18 | # Removes and returns the first item in the queue 19 | def dequeue(self): 20 | assert not self.isEmpty(), "Cannot dequeue from and empty queue." 21 | return self._qlist.pop(0) 22 | -------------------------------------------------------------------------------- /insertionSort_algorithm.py: -------------------------------------------------------------------------------- 1 | ''' Insertion Sort ''' 2 | def insertionSort(seq): 3 | n = len(seq) 4 | # Starts with the first item as the only sorted entry 5 | for i in range(1, n): 6 | # save the value to be positioned 7 | value = seq[i] 8 | # Find the position where value fits in the ordered part of the list 9 | pos = i 10 | while pos > 0 and value < seq[pos - 1]: 11 | # shift the items to the right during the search 12 | seq[pos] = seq[pos - 1] 13 | pos -= 1 14 | seq[pos] = value 15 | print seq 16 | return seq 17 | 18 | insertionSort([12, 5, 13, 8, 9, 65]) 19 | -------------------------------------------------------------------------------- /longest sequence of repeated digits.py: -------------------------------------------------------------------------------- 1 | # Longest sequence of repeated digits 2 | 3 | seq = [] 4 | limitOfList = eval(input("Enter the size of a list")) 5 | while len(seq) <= limitOfList: 6 | i = eval(input()) 7 | seq.append(i) 8 | # print(seq) // Debugging Purposes 9 | # End of the loop 10 | 11 | 12 | seq[0] = New_Digit 13 | Current_Run_Value = New_Digit 14 | Current_Run_Length = 1 15 | Max_Run = 1 16 | while 17 | -------------------------------------------------------------------------------- /numInt.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Numerical Integration (Quadrature) using Python" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "Sometimes you'll encounter definite integrals that cannot be solved analytically. The **`scipy`** library for Python contains numerous functions for scientific computing and data analysis, which include a few algorithms for finding the definite integrals of functions. The **`quad`** function which determines where the integral is more difficult to calculate and expends more effort there. The examples below demonstrate a few common uses of the function." 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": {}, 20 | "source": [ 21 | "The following lines import the functions for integrating and plotting." 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 1, 27 | "metadata": { 28 | "collapsed": false 29 | }, 30 | "outputs": [], 31 | "source": [ 32 | "%matplotlib inline" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 1, 38 | "metadata": { 39 | "collapsed": false 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "from math import *\n", 44 | "from pylab import *\n", 45 | "from scipy.integrate import quad #.integrate import *" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "The integrand must be defined as a function (called **`intgrd1`** below). In the simplest case, the integrand only\n", 53 | "depends on the variable of integration. The other arguments of the **`quad`** function are the\n", 54 | "integrand, the lower limit, and the upper limit. It returns both the result and an estimate of the error. " 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 2, 60 | "metadata": { 61 | "collapsed": false 62 | }, 63 | "outputs": [ 64 | { 65 | "name": "stdout", 66 | "output_type": "stream", 67 | "text": [ 68 | "(0.7273243567064205, 8.074922471861484e-15)\n" 69 | ] 70 | } 71 | ], 72 | "source": [ 73 | "def intgrnd1(x):\n", 74 | " return cos(x)**2\n", 75 | "\n", 76 | "print(quad(intgrnd1, 0.0, 1.0))" 77 | ] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "metadata": {}, 82 | "source": [ 83 | "It is easy to separate the two outputs as shown below. This is useful if you want to use the result in a calculation." 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 3, 89 | "metadata": { 90 | "collapsed": false 91 | }, 92 | "outputs": [ 93 | { 94 | "name": "stdout", 95 | "output_type": "stream", 96 | "text": [ 97 | "0.727324356706\n" 98 | ] 99 | } 100 | ], 101 | "source": [ 102 | "result, err = quad(intgrnd1, 0.0, 1.0)\n", 103 | "print(result)" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "Suppose you want to find the integral for several different upper limits. You could define\n", 111 | "the integral as a function of the upper limit, then call the function for various upper limits." 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 4, 117 | "metadata": { 118 | "collapsed": false 119 | }, 120 | "outputs": [ 121 | { 122 | "name": "stdout", 123 | "output_type": "stream", 124 | "text": [ 125 | "(0.8107993761730178, 9.001681357789979e-15)\n", 126 | "(1.4301461254502685, 1.5877811570533458e-14)\n" 127 | ] 128 | } 129 | ], 130 | "source": [ 131 | "def intgrl1(xup): # make the upper limit a variable\n", 132 | " return quad(intgrnd1, 0.0, xup)\n", 133 | "\n", 134 | "print (intgrl1(2.0))\n", 135 | "print (intgrl1(3.0))" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "Suppose that you want to make a graph of the integral as a function of the upper limit. You\n", 143 | "might try to make a list of upper limits, then call the **`intgrl1`** function to get a list of\n", 144 | "results with the various upper limits. However, that will not work, because it is not a \"vectorized\" function which can handle a list of inputs. (Many functions like **`cos`**, which returns the cosine of the argument, are vectorized.) \n", 145 | "The lines below make vectorized version of the function (**`vec_intgrl1`**), which has a different name than the original function. It returns the integral for each upper limit in the list (**`xupper`**) and their uncertainty estimates." 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 5, 151 | "metadata": { 152 | "collapsed": false 153 | }, 154 | "outputs": [ 155 | { 156 | "name": "stdout", 157 | "output_type": "stream", 158 | "text": [ 159 | "(array([ 0.72732436, 0.76663098, 0.78261427, 0.78539559, 0.78685786,\n", 160 | " 0.79906004, 0.83262802, 0.89533676, 0.99107292, 1.11931618,\n", 161 | " 1.2752087 , 1.45020332, 1.63320403, 1.81204654, 1.97512139,\n", 162 | " 2.11292306, 2.21931832, 2.29236456, 2.33456907, 2.35255443,\n", 163 | " 2.35617485, 2.3572013 , 2.3677509 , 2.39867003, 2.45808711,\n", 164 | " 2.55032801, 2.67533878, 2.82869293, 3.00218198, 3.18491082,\n", 165 | " 3.36475144, 3.52996119, 3.6707497 , 3.78058517, 3.85706598,\n", 166 | " 3.90224112, 3.92233678, 3.92692561, 3.92764936, 3.93666551,\n", 167 | " 3.96502508, 4.02119802, 4.10994306, 4.23167274, 4.38239834,\n", 168 | " 4.55426214, 4.73658589, 4.91729562, 5.08453273, 5.22823631]), array([ 8.07492247e-15, 8.51131370e-15, 8.68876386e-15,\n", 169 | " 8.71964263e-15, 8.73587713e-15, 8.87134856e-15,\n", 170 | " 9.24402794e-15, 9.94023489e-15, 1.10031198e-14,\n", 171 | " 1.24269059e-14, 1.41576606e-14, 1.61004912e-14,\n", 172 | " 1.81322072e-14, 2.01177579e-14, 2.19282524e-14,\n", 173 | " 2.34581584e-14, 2.46393830e-14, 2.54503592e-14,\n", 174 | " 2.59189234e-14, 2.61186009e-14, 2.61587956e-14,\n", 175 | " 5.68525062e-14, 5.81482583e-13, 3.19520894e-12,\n", 176 | " 1.37317834e-11, 4.97258155e-11, 1.56439403e-10,\n", 177 | " 4.48117763e-10, 1.18070833e-09, 2.81476295e-09,\n", 178 | " 6.33396378e-09, 1.32602983e-08, 2.53234782e-08,\n", 179 | " 4.39379850e-08, 4.28220346e-14, 4.33235794e-14,\n", 180 | " 4.35466861e-14, 1.81440888e-08, 4.36056675e-14,\n", 181 | " 4.37057670e-14, 4.40206216e-14, 4.55162268e-14,\n", 182 | " 5.85779831e-14, 7.09909833e-14, 7.41841620e-14,\n", 183 | " 5.50213900e-14, 5.25866785e-14, 1.63712793e-13,\n", 184 | " 7.16903967e-13, 2.05420338e-12]))\n" 185 | ] 186 | } 187 | ], 188 | "source": [ 189 | "vec_intgrl1 = vectorize(intgrl1)\n", 190 | "xupper = linspace(1.0, 10.0, 50) # make a list of upper limits\n", 191 | "print vec_intgrl1(xupper)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "To create plot of the integral vs. the upper limit, send the results to a separate list from the errors." 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 6, 204 | "metadata": { 205 | "collapsed": false 206 | }, 207 | "outputs": [ 208 | { 209 | "data": { 210 | "image/png": [ 211 | "iVBORw0KGgoAAAANSUhEUgAAAXoAAAEPCAYAAABMTw/iAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n", 212 | "AAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl4VdW9//H3CYRQCGFQSECwIGXKQHIYEkVSE5lUDAii\n", 213 | "AipcQGsvdcCpTr+nxva5oBdtRVHbWhVFi9QBZBAKggdTBiMCCjJYhChhksEQMpBx//5YTYALZIDs\n", 214 | "s8/Z+byeZz8Zz1lfwX5cXXvt7/JYlmUhIiKuFeJ0ASIiYi8FvYiIyynoRURcTkEvIuJyCnoREZdT\n", 215 | "0IuIuJytQZ+Tk8OoUaPo0aMH0dHRrFu3zs7hRETkLBra+eb33Xcf1113He+//z6lpaXk5+fbOZyI\n", 216 | "iJyFx64Hpo4dO4bX62XXrl12vL2IiNSQbUs3u3fvpnXr1kyYMIFevXpx5513UlBQYNdwIiJyDrYF\n", 217 | "fWlpKRs2bGDy5Mls2LCBpk2b8vTTT9s1nIiInINta/Tt27enffv29O3bF4BRo0adEfQej8eu4UVE\n", 218 | "XK02q+62zeijoqLo0KED3377LQCffPIJMTExZ/yeZVkBdz355JOO16CaVFN9rEs11eyqLVt33bz4\n", 219 | "4ovceuutFBcX07lzZ9544w07hxMRkbOwNejj4+P54osv7BxCRESqoSdjzyIlJcXpEs6gmmpGNdVc\n", 220 | "INalmuxh2z76Gg3u8ZzXepOISH1W2+zUjF5ExOUU9CIiLqegFxFxOQW9iIjLKehFRFxOQS8i4nIK\n", 221 | "ehERl1PQi4i4nIJeRMTlFPQiIi6noBcRcTkFvYiIyynoRURcTkEvIuJyCnoREZdT0IuIuJyCXkTE\n", 222 | "5RT0IiIup6AXEXE5Bb2IiMsp6EVEXE5BLyISRMrLa/8aBb2ISJDIyYHhw2v/OgW9iEgQ+Oor6NMH\n", 223 | "Lrus9q9V0IuIBLi334aBA+H3v4cZM2r/+oZ1X5KIiNSF4mJ44AH45z9h5UqIizu/97E96Dt27EhE\n", 224 | "RAQNGjQgNDSUzMxMu4cUEQl6e/fCTTdB69bwxRfQosX5v5ftQe/xePD5fLRq1cruoUREXOHLL2HY\n", 225 | "MPjNb+DRRyHkAhfZ/bJ0Y1mWP4YREQl6n3wCY8fCX/8KN9xQN+9p+81Yj8fDwIED6dOnD6+++qrd\n", 226 | "w4mIBK1//MOE/Pvv113Igx9m9KtXr6Zt27YcOnSIQYMG0b17d5KTk+0eVkQkqLz0EkybZmb0PXvW\n", 227 | "7XvbHvRt27YFoHXr1owYMYLMzMzTgj49Pb3y85SUFFJSUuwuSUQkYFgWpKfD3/8OGRnQqdOZv+Pz\n", 228 | "+fD5fOc9hseycQG9oKCAsrIymjVrRn5+PoMHD+bJJ59k8ODBZnCPR+v3IlJvlZWZG65ffAFLlkCb\n", 229 | "NjV7XW2z09YZ/cGDBxkxYgQApaWl3HrrrZUhLyJSnxUXm/X4nBz49FOIiLBvLFtn9NUOrhm9iNRD\n", 230 | "RUVmj3xICMydC2FhtXt9bbNTLRBERPzoxAkYORIaNYL33qt9yJ8PBb2IiJ8UFpptk+HhMGcOhIb6\n", 231 | "Z1wFvYiIHxQUmKddL7oI3nnHfyEPCnoREdvl58P110PbtvDWW9DQz+0kFfQiIjbKy4PrroOOHeGN\n", 232 | "N6BBA//XoKAXEbHJ8eNwzTXQrRv87W/OhDwo6EVEbJGba0I+Lg7+/OcL70B5IRT0IiJ17NgxGDIE\n", 233 | "4uNNDxsnQx4U9CIidaoi5Hv3DoyQBwW9iEidycmBwYMhMRFefBE8HqcrMhT0IiJ14KefYNAguPxy\n", 234 | "c4B3oIQ8KOhFRC5YRchfeSU8/3xghTwo6EVELsjBg3D11XDVVfCnPwVeyIOCXkTkvP3wAyQnw/Dh\n", 235 | "8OyzgRny4KfDwUVE3GbHDnPj9f77YcoUp6upmoJeRKSWNm40bQ2mToUJE5yupnoKehGRWvjXv0w/\n", 236 | "+VdegRtvdLqamlHQi4jU0NKlcPvtps1wMJ2KqpuxIiI18PbbMG4cfPRRcIU8aEYvIlKlsjJ4/HFz\n", 237 | "7N/KlRAb63RFtaegFxE5h2PHYOxYczpUZiZcfLHTFZ0fLd2IiJzFv/9t2hl07AjLlgVvyIOCXkTk\n", 238 | "DMuXQ//+cN99pgOlP893tYOWbkRE/sOyTNfJqVPhH/8wbQ3cQEEvIgLs3w///d+QlQVr10KnTk5X\n", 239 | "VHe0dCMi9ZplwezZkJAAPXvC55+7K+RBM3oRqcf27oW77oI9e2DJEujVy+mK7KEZvYjUO5YFs2aB\n", 240 | "1wt9+sAXX7g35EEzehGpZ776Ch59FA4cMNsmExKcrsh+ts/oy8rK8Hq9pKWl2T2UiMg5ff45DBsG\n", 241 | "115rToPKzKwfIQ9+CPoZM2YQHR2NJ1A78ouIa1kWrFplgv3mm+Gaa2DXLnjggeDfG18btgZ9dnY2\n", 242 | "H3/8MXfccQeWZdk5lIhIpeJiWLQIfvlLuOMO08bg3/+GyZOhcWOnq/M/W9fo77//fqZPn05ubq6d\n", 243 | "w4iI8NNP8PHHsGAB/POfEB0N99xjZvINGjhdnbNsC/pFixbRpk0bvF4vPp/vnL+Xnp5e+XlKSgop\n", 244 | "KSl2lSQiLlJcbGbpy5ebcF+/HlJTzTr8jBkQFeV0hXXH5/NVmaPV8Vg2rak8/vjjzJ49m4YNG3Li\n", 245 | "xAlyc3O58cYbeeutt04O7vFoSUdEzqqoCPLy4PhxyM42Z7Ru337y4w8/QIcOpk3B8OEwYAA0aeJ0\n", 246 | "1f5R2+y0LehPtWrVKp599lkWLlx4+uAKepGgZVlmuSQ7+/Rr/34oLDQz7uJiE9gVH0tKzOvOdpWU\n", 247 | "mFCvCHfLgmbNzNW2LXTvDt26nfzYuTOEhTn9p+CM2man3/bRa9eNSHDLzjY7WFatgtWrYfduE7Tt\n", 248 | "259+9e1rZtaNGpkrLOzk56Gh4PGc/QoNPRns4eH1N8Tt4JcZ/TkH14xeJGDt22fWvyvCPTfX7GK5\n", 249 | "6ipIToYuXUwgi/8F5NLNOQdX0IsElPJyWLECXn755P7zq64yV48eEKKmKQEhYJduRCRw5eSY3i+v\n", 250 | "vGKWTH7zG9PRUTN2d1DQi9Rj27fDH/9oDr6+9lp47TW48kqzZi7uoaAXqYeOH4ff/97M4u+9F7Zt\n", 251 | "c9e+czmdgl6kHrEsmDsXHnoIBg6ELVsgMtLpqsRuCnqReuKbb0xLgJ9+Mueh9uvndEXiL7qHLuJy\n", 252 | "x4/Dgw9CSgqMHGkO2VDI1y+a0Yu42JYtMGoUJCaaGX2bNk5XJE7QjF7EpWbPNk2+HnsM3npLIV+f\n", 253 | "aUYv4jInTsCUKfDpp7ByJcTFOV2ROE0zehEX2b3b7IM/csSsxSvkBRT0Iq6xcCEkJcG4cWZXTUSE\n", 254 | "0xVJoNDSjUiQsyyYPh1efBE++giuuMLpiiTQKOhFglh5uTnoesUKWLcOLrnE6YokECnoRYJUUZFZ\n", 255 | "pjlwADIyoEULpyuSQHXOoI+r4i6Ox+Ph66+/tqUgEanesWMwYgS0bGkOwm7c2OmKJJCdsx99VlZW\n", 256 | "lS/s2LHjhQ+ufvQitbZ/v+k02a+fWZdv0MDpisTfdPCIiIvt2AHXXAN33AGPP652wvVVbbOz2u2V\n", 257 | "a9eupW/fvjRt2pTQ0FBCQkKI0L4tEb/btMn0q/l//w+eeEIhLzVXbdDffffd/P3vf6dr166cOHGC\n", 258 | "1157jcmTJ/ujNhH5j/XrYcgQmDkTJk1yuhoJNjV6YKpLly6UlZXRoEEDJkyYwNKlS+2uS0T+4/PP\n", 259 | "4brr4K9/hRtvdLoaCUbVbq9s2rQpRUVFxMfH89vf/paoqCitq4v4yerVZnfNG2/A0KFOVyPBqtoZ\n", 260 | "/ezZsykvL2fmzJk0adKE7OxsPvjgA3/UJlKvrVoFN9xgulAq5OVCVLnrprS0lPHjx/POO+/YM7h2\n", 261 | "3Yic1cqVcMst8O67MGCA09VIoKnTXTcNGzbk+++/p6io6IILE5GaWbYMRo+G999XyEvdqHaNvlOn\n", 262 | "TvTv359hw4bRpEkTwPzX5IEHHrC9OJH6ZulS09Zg3jzTblikLlQb9J07d6Zz586Ul5eTl5eHZVl4\n", 263 | "tIFXpM4tWQLjx6sDpdQ9PRkrEgA+/hj+679gwQK4/HKnq5FAV9vsrHZGn5aWdtqbejwemjdvTp8+\n", 264 | "fbjrrrtoXEU3pRMnTnDVVVdRVFREcXExw4cPZ9q0aTUuTqQ+WLwYJkw4eXCISF2rdkZ/7733cvjw\n", 265 | "YcaMGYNlWcydO5eIiAhCQkLIzc1l9uzZVQ5QUFBAkyZNKC0tpX///jz77LP079/fDK4ZvdRzixbB\n", 266 | "xIkKeamdOp/Rr1mzhvXr11d+PWzYMPr06cP69euJiYmpdoCKG7jFxcWUlZXRqlWrGhcn4mYLF5rm\n", 267 | "ZIsWQWKi09WIm1X7wFR+fj7ff/995dfff/89+fn5ADRq1KjaAcrLy0lISCAyMpLU1FSio6MvoFwR\n", 268 | "d1iwQCEv/lPtjP65554jOTmZyy67DIBdu3bx8ssvk5+fz/jx46sdICQkhE2bNnHs2DGGDBmCz+cj\n", 269 | "JSWl8ufp6emVn6ekpJz2MxE3mjsX7rvPrM336eN0NRIMfD4fPp/vvF9fo103J06cYMeOHQB069at\n", 270 | "yhuwVfnDH/7Az372Mx566CEzuNbopZ559VVITzf75as4xE2kSnXejz4/P5/p06czc+ZM4uPj2bNn\n", 271 | "D4sWLarRmx8+fJicnBwACgsLWb58OV6vt8bFibjJH/8I//M/4PMp5MW/qg36CRMm0KhRI9asWQNA\n", 272 | "u3bteOKJJ2r05vv37+fqq68mISGBpKQk0tLSGKBnuqWesSwzi//LX8wh3l26OF2R1DfVLt307t2b\n", 273 | "L7/8Eq/Xy8aNGwGIj4/nq6++uvDBtXQjLmdZ8OCDpknZP/8JkZFOVyRuUOfbK8PCwigsLKz8+rvv\n", 274 | "viMsLOz8qhOpR8rK4Ne/hi1b4NNPoWVLpyuS+qraoE9PT+eaa64hOzubsWPHsnr1ambNmuWH0kSC\n", 275 | "V34+3H47HDsGy5dDeLjTFUl9VqNdN4cPH2bdunUAJCUl0bp167oZXEs34kJ79sCwYZCQAH/+M+j/\n", 276 | "AEtdq212Vhv0AwYMYMWKFdV+73wo6MVtPv8cRo6EKVPgoYdAjV7FDnW2Rl9YWEhBQQGHDh3i6NGj\n", 277 | "ld/Pzc1l7969F1aliAvNmWMehHrtNUhLc7oakZPOGfR/+ctfmDFjBvv27aN3796V32/WrBl33323\n", 278 | "X4oTCQbl5Wb75OzZsGKF9shL4Kl26eaFF17g3nvvtWdwLd1IkMvPN33k9+0zp0K1aeN0RVIf1Pka\n", 279 | "PZgOlllZWZSWllZ+b9y4cedX4amDK+gliK1da06E6t8fXnlFN13Ff+p8H/1tt93Grl27SEhIoEGD\n", 280 | "BpXfr4ugFwlGRUVmqWbWLHjpJXPzVSSQVRv0X375JVu3btU5sSLAxo3m8O5f/AK++kpLNRIcqu11\n", 281 | "Exsby/79+/1Ri0jAKimBP/wBhgyBRx6BDz9UyEvwqHZGf+jQIaKjo0lMTKxsfeDxeFiwYIHtxYkE\n", 282 | "gjVrzLbJiy6CDRugfXunKxKpnRq1QBCpj9auNWvxO3bAk0+a3TVawZRgVKNdN7YNrl03EoDWrTMB\n", 283 | "v307PPGE2VlTg1MzRfymzg4eufLKKwEIDw+nWbNmp10REREXXqlIALEsM4O/9lq45Razk+bbb+HO\n", 284 | "OxXyEvw0o5d6y7Jg/Xr44ANzlZWZG60TJijcJbDV+T56ETcpKzM3Vz/80FxhYXDjjaZPTe/eWoMX\n", 285 | "d1LQi2sdOQLffGOuLVvMx82b4ZJLTLgvXgwxMQp3cT8t3Yhj8vNh/344fBiKi81e9Yqr4uuyMtM0\n", 286 | "zLLMdernhYWQm2sO96i4cnMhJwe++878PCbm9Cs2Ftq2dfqfXOTC2NLrxi4KevfLzobVq81aeHa2\n", 287 | "CfaKq6TEhO7FF5sllNDQk1ejRuZjgwYQEmJm3RUfK67GjaF589OviAjzsVMnM3PXbF3cSEEvjikr\n", 288 | "g6+/Nmvgq1ebKz8f+vWDyy+HSy+Fdu1MuLdtawJZQSxSewp68butW+HVV00/9osvhiuvPHl17aow\n", 289 | "F6lr2nUjflFYCO+9ZwJ+506YOBEyM+Gyy5yuTET+L83opVa2b4eXX4Z33oGkJPjVr2DoULOeLiL+\n", 290 | "UWdPxoqc6uhRuOce+OUvzdr6hg3w8cdwww0KeZFAp6CXKpWWmsM1unc3Wxq3bTPten/+c6crE5Ga\n", 291 | "0hq9nNOKFaY9b5s2OvRaJJgp6OUM338P998PmzbBc8+Z5RntnBEJXrYu3ezZs4fU1FRiYmKIjY3l\n", 292 | "hRdesHM4qQPz5kHfvtCrl9k2OWKEQl4k2Nm66+bAgQMcOHCAhIQE8vLy6N27N/Pnz6dHjx5mcO26\n", 293 | "CRjFxfDb38JHH8HcuZCY6HRFInIuAbXrJioqioSEBMD0te/Rowf79u2zc0g5D7t3Q//+kJVldtMo\n", 294 | "5EXcxW+7brKysti4cSNJSUn+GlJqYN48sx9+7FjzecuWTlckInXNLzdj8/LyGDVqFDNmzCA8PPy0\n", 295 | "n516Jm1KSgopKSn+KKneO3WpZtEizeJFApnP58Pn8533621/MrakpITrr7+ea6+9lilTppw+uNbo\n", 296 | "HZGTY26yhofDW29pFi8SbAJqjd6yLCZNmkR0dPQZIS/OyM6G5GTTl33+fIW8SH1ga9CvXr2at99+\n", 297 | "m08//RSv14vX62Xp0qV2DilV+OYb01Hy9tvhhRdMr3cRcT81NasnVq2Cm2+GP/3J3HgVkeClNsVy\n", 298 | "hn/8A+6+2xyAPWCA09WIiL8p6F3u+edNG4PlyyE+3ulqRMQJCnqXsix48kl4/31zpN+llzpdkYg4\n", 299 | "RUHvQpYFjz4KS5eatfnWrZ2uSEScpKB3GcsynSczMmDlSrjoIqcrEhGnKehdpLzc3HTdsMH0j2/R\n", 300 | "wumKRCQQKOhdoqzMnN+6YwcsWwYREU5XJCKBQkHvAqWlMGGCeep16VLT2kBEpIKCPsiVlJgnXY8e\n", 301 | "hcWLoUkTpysSkUCjoA9iJSVw661w/DgsWACNGztdkYgEIgV9kCopMa0MCgpMH3mFvIici4I+CJWU\n", 302 | "wJgxUFgIH34IYWFOVyQigcxvJ0xJ3agI+RMnFPIiUjOa0QeRkhIYPdqcDvXBBwp5EakZzeiDREXI\n", 303 | "l5SY/jUKeRGpKQV9ECgqgltuMSH/3nsKeRGpHQV9gCsogBtuAI9HM3kROT8K+gB2/Dhcdx1cfDHM\n", 304 | "nQuNGjldkYgEIwV9gPrpJxg0CLp3hzffhIa6bS4i50lBH4B+/BFSU6F/f3jlFQjR35KIXABFSIDJ\n", 305 | "zoZf/tKsy0+fbtbmRUQuhBYEAsiuXTBwIEyeDA895HQ1IuIWmtEHiMxMSE6Ghx9WyItI3dKMPgC8\n", 306 | "956Zxb/+OqSlOV2NiLiNgt5BlgXTpsGf/wzLl0NCgtMViYgbKegdUlQEd90FW7bAunXQrp3TFYmI\n", 307 | "W2mN3gFHjpg98rm5sGqVQl5E7KWg97Pt2+Hyy6FfP9PSoGlTpysSEbezNegnTpxIZGQkcXFxdg4T\n", 308 | "FCzLPPyUnAyPPw5PP60HoUTEPzyWZVl2vXlGRgbh4eGMGzeOzZs3nzm4x4ONwweM/fth0iQ4dAje\n", 309 | "fhu6dXO6IhEJZrXNTlvnlMnJybRs2dLOIQLevHng9UKfPrBmjUJeRPxPu25skpsLU6bAZ5+ZsL/i\n", 310 | "CqcrEpH6SqvEdcyyYPFisye+QQPYtEkhLyLOcnxGn56eXvl5SkoKKSkpjtVyoXw+eOIJOHYMZs40\n", 311 | "veRFRC6Uz+fD5/Od9+ttvRkLkJWVRVpamqtvxmZmmoDftQueegrGjDGzeREROwTUzdgxY8bQr18/\n", 312 | "vv32Wzp06MAbb7xh53B+t3mzaSc8ciTcdJPZI3/bbQp5EQksts/oqxw8CGf0Bw+aB53mzoUdO+DR\n", 313 | "R+HXv4af/czpykSkvqhtdiroa+DoUfjwQ3j3XVi/Hq6/Hm65BQYP1mHdIuJ/CvoLVF5u1tq//hq+\n", 314 | "+go+/xzWrjWhfsst5gZrkyZOVyki9ZmCvgrFxebQ7YorJ8d8PHIEtm41wb55M7RqBfHx0LOnedhp\n", 315 | "8GBo1sxvZYqIVMkVQZ+TA998AwcOmIOyf/zRrI1XfJ6TA6WlZ7/Kysys/FxXixbQsuXpV6tW5onV\n", 316 | "inCv5w/zikiAC7qgLy62+Pprs0Ty+edmq2J2NsTEmPa9bdqYKzLy5OctWkBoKDRsePrVoMHJKyTk\n", 317 | "9MvjMevpOmxbRIJd0AV906YWnTpBUhIkJpqPMTEmuEVE5ExBF/S5uZbWv0VEaiHogj7Qdt2IiAS6\n", 318 | "gHoyVkREnKegFxFxOQW9iIjLKehFRFxOQS8i4nIKehERl1PQi4i4nIJeRMTlFPQiIi6noBcRcTkF\n", 319 | "vYiIyynoRURcTkEvIuJyCnoREZdT0IuIuJyCXkTE5RT0IiIup6AXEXE5Bb2IiMsp6EVEXM7WoF+6\n", 320 | "dCndu3enS5cuPPPMM3YOJSIi52Bb0JeVlXH33XezdOlStm7dypw5c9i2bZtdw9Upn8/ndAlnUE01\n", 321 | "o5pqLhDrUk32sC3oMzMz+cUvfkHHjh0JDQ1l9OjRfPTRR3YNV6cC8S9WNdWMaqq5QKxLNdnDtqDf\n", 322 | "u3cvHTp0qPy6ffv27N27167hRETkHGwLeo/HY9dbi4hILXgsy7LseON169aRnp7O0qVLAZg2bRoh\n", 323 | "ISE88sgjJwfXfwxERM5LbaLbtqAvLS2lW7durFixgnbt2pGYmMicOXPo0aOHHcOJiMg5NLTtjRs2\n", 324 | "ZObMmQwZMoSysjImTZqkkBcRcYBtM3oREQkMjjwZO3HiRCIjI4mLi3Ni+LPas2cPqampxMTEEBsb\n", 325 | "ywsvvOB0SQCcOHGCpKQkEhISiI6O5rHHHnO6JMA8J+H1eklLS3O6lEodO3akZ8+eeL1eEhMTnS4H\n", 326 | "gJycHEaNGkWPHj2Ijo5m3bp1jtazY8cOvF5v5dW8efOA+Hd92rRpxMTEEBcXx9ixYykqKnK6JABm\n", 327 | "zJhBXFwcsbGxzJgxw5EazpaXR48eZdCgQXTt2pXBgweTk5NT9ZtYDvjss8+sDRs2WLGxsU4Mf1b7\n", 328 | "9++3Nm7caFmWZR0/ftzq2rWrtXXrVoerMvLz8y3LsqySkhIrKSnJysjIcLgiy3ruueessWPHWmlp\n", 329 | "aU6XUqljx47WkSNHnC7jNOPGjbNee+01y7LM319OTo7DFZ1UVlZmRUVFWT/88IOjdezevdvq1KmT\n", 330 | "deLECcuyLOvmm2+2Zs2a5WhNlmVZmzdvtmJjY63CwkKrtLTUGjhwoLVz506/13G2vHz44YetZ555\n", 331 | "xrIsy3r66aetRx55pMr3cGRGn5ycTMuWLZ0Y+pyioqJISEgAIDw8nB49erBv3z6HqzKaNGkCQHFx\n", 332 | "MWVlZbRq1crRerKzs/n444+54447anXn3x8CqZ5jx46RkZHBxIkTAXPfqnnz5g5XddInn3xC586d\n", 333 | "T3vexQkRERGEhoZSUFBAaWkpBQUFXHLJJY7WBLB9+3aSkpJo3LgxDRo04KqrruLDDz/0ex1ny8sF\n", 334 | "CxYwfvx4AMaPH8/8+fOrfA81NTuLrKwsNm7cSFJSktOlAFBeXk5CQgKRkZGkpqYSHR3taD33338/\n", 335 | "06dPJyQksP718Xg8DBw4kD59+vDqq686XQ67d++mdevWTJgwgV69enHnnXdSUFDgdFmV3n33XcaO\n", 336 | "Het0GbRq1YoHH3yQSy+9lHbt2tGiRQsGDhzodFnExsaSkZHB0aNHKSgoYPHixWRnZztdFgAHDx4k\n", 337 | "MjISgMjISA4ePFjl7wfW/1IDQF5eHqNGjWLGjBmEh4c7XQ4AISEhbNq0iezsbD777DNHH8letGgR\n", 338 | "bdq0wev1BtTsGWD16tVs3LiRJUuW8NJLL5GRkeFoPaWlpWzYsIHJkyezYcMGmjZtytNPP+1oTRWK\n", 339 | "i4tZuHAhN910k9Ol8N133/H888+TlZXFvn37yMvL45133nG6LLp3784jjzzC4MGDufbaa/F6vQE3\n", 340 | "uQEzwanumaTAq9pBJSUl3Hjjjdx2223ccMMNTpdzhubNmzN06FDWr1/vWA1r1qxhwYIFdOrUiTFj\n", 341 | "xrBy5UrGjRvnWD2natu2LQCtW7dmxIgRZGZmOlpP+/btad++PX379gVg1KhRbNiwwdGaKixZsoTe\n", 342 | "vXvTunVrp0th/fr19OvXj4suuoiGDRsycuRI1qxZ43RZgLkRun79elatWkWLFi3o1q2b0yUBZhZ/\n", 343 | "4MABAPbv30+bNm2q/H0F/X9YlsWkSZOIjo5mypQpTpdT6fDhw5V31AsLC1m+fDler9exeqZOncqe\n", 344 | "PXvYvXs37777LldffTVvvfWWY/VUKCgo4Pjx4wDk5+ezbNkyx3d1RUVF0aFDB7799lvArInHxMQ4\n", 345 | "WlOFOXPmMGbMGKfLAMzMed26dRQWFmJZFp988onjy5MVfvzxRwB++OEH5s2bFxBLXQDDhg3jzTff\n", 346 | "BODNN9+sfmJq153iqowePdpq27at1ahRI6t9+/bW66+/7kQZp8nIyLA8Ho8VHx9vJSQkWAkJCdaS\n", 347 | "JUucLsv6+uuvLa/Xa8XHx1txcXHW//7v/zpdUiWfzxcwu2527dplxcfHW/Hx8VZMTIw1depUp0uy\n", 348 | "LMuyNm3aZPXp08fq2bOnNWLEiIDYdZOXl2dddNFFVm5urtOlVHrmmWes6OhoKzY21ho3bpxVXFzs\n", 349 | "dEmWZVlWcnKyFR0dbcXHx1srV650pIaKvAwNDa3MyyNHjlgDBgywunTpYg0aNMj66aefqnwPPTAl\n", 350 | "IuJyWroREXE5Bb2IiMsp6EVEXE5BLyLicgp6ERGXU9CLiLicgl6kllJSUiqfcB06dCi5ubk1fu3C\n", 351 | "hQt55plnAJg/fz7btm2zpUaRUynoRapgWdYZPX1O7SuyePFiIiIiavx+aWlplecmz58/n61bt9ZN\n", 352 | "oSJVUNBLUMnKyjqttcGzzz7LU089BZiZ9pQpU/B6vcTFxfHFF18AkJ6ezu23306/fv3o2rUrf/vb\n", 353 | "3ypfP336dBITE4mPjyc9Pb1yjG7dujF+/Hji4uKq7FjYsWNHjh49SlZWFt27d2fChAl069aNW2+9\n", 354 | "lWXLlnHllVfStWvXylpmzZrFPffcw9q1a1m4cCEPP/wwXq+XXbt21fUflUgl286MFfGHUzv3eTwe\n", 355 | "CgsL2bhxY2Uf+M2bNwOwZcsW1q1bR15eHl6vl6FDh7J582Z27txJZmYm5eXlDB8+nIyMDDp06MDO\n", 356 | "nTuZPXsdgEAPAAACCElEQVR2tSdVnTq7/+677/jggw+Ijo6mb9++zJ07l9WrV7NgwQKmTp3KvHnz\n", 357 | "Kn/3iiuuYNiwYaSlpTFy5Egb/mRETlLQS9A7dWmlolFXcnIyubm5HDt2DI/Hw/DhwwkLCyMsLIzU\n", 358 | "1FQyMzPJyMhg2bJllU3i8vPz2blzJx06dODnP/95rY8j7NSpU2XTspiYmMqe6rGxsWRlZVVbu4hd\n", 359 | "FPQSVBo2bEh5eXnl14WFhVX24j7Xzyq+/9hjj/GrX/3qtJ9lZWXRtGnTWtcWFhZW+XlISAiNGjWq\n", 360 | "/Ly0tLRW9YnUJa3RS1CJjIzkxx9/5OjRoxQVFbFo0aLKn1mWxdy5cwH417/+RYsWLYiIiMCyLD76\n", 361 | "6COKioo4cuQIPp+PxMREhgwZwuuvv05+fj4Ae/fu5dChQ377Z2nWrFmtduyInC/N6CWohIaG8rvf\n", 362 | "/Y7ExEQuueSS0/qWezweGjduTK9evSgtLeX111+v/H7Pnj1JTU3l8OHD/O53vyMqKoqoqCi2bdvG\n", 363 | "FVdcAZjgffvtt2t0Ys/Z/N/XnPr1qfcRKj4fPXo0d955Jy+++CLvvfcel112Wa3HFKkJtSkW10hN\n", 364 | "TeW5556jV69ep33/qaeeIjw8nAcffNChykScpaUbqRe0Fi71mWb0IiIupxm9iIjLKehFRFxOQS8i\n", 365 | "4nIKehERl1PQi4i4nIJeRMTl/j8DAQaLVW66ogAAAABJRU5ErkJggg==\n" 366 | ], 367 | "text/plain": [ 368 | "" 369 | ] 370 | }, 371 | "metadata": {}, 372 | "output_type": "display_data" 373 | } 374 | ], 375 | "source": [ 376 | "results, errs = vec_intgrl1(xupper)\n", 377 | "figure()\n", 378 | "plot(xupper, results)\n", 379 | "xlabel('upper limit')\n", 380 | "ylabel('integral')\n", 381 | "show()" 382 | ] 383 | }, 384 | { 385 | "cell_type": "markdown", 386 | "metadata": {}, 387 | "source": [ 388 | "It is also possible to perform an integral that depends on another parameter in addition to the variable of integration. The function **`intgrnd2`** is defined as a function of the parameter **`n`**. The function **`intgrl2`** returns the integral as a funciton of the parameter, with the limits of the integration fixed. After the function is vectorized (called **`vec_intgrl2`**), the values of the integral for the each parameter in a list can be found. This makes it easy to plot the integral vs. the parameter." 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": 7, 394 | "metadata": { 395 | "collapsed": false 396 | }, 397 | "outputs": [ 398 | { 399 | "data": { 400 | "image/png": [ 401 | "iVBORw0KGgoAAAANSUhEUgAAAYQAAAEPCAYAAABCyrPIAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\n", 402 | "AAALEgAACxIB0t1+/AAAGIZJREFUeJzt3X9M1Pcdx/HXIVfF360/B4dBBeHwB1JB61w3qoNTM2/+\n", 403 | "ykJNJ7GoREOcG91M/9jKkk0ljnRatgUbXW1n0WSdYho9Jm6XaS1lDqddcVNbcedZTZ2zRsEf3L77\n", 404 | "w/NSCsiv+3J4PB/JJfc9Pt8v72+i9+Lz+Xw/36/FMAxDAIBeLyLUBQAAegYCAQAgiUAAAPgRCAAA\n", 405 | "SQQCAMCPQAAASDI5EFwul5KSkpSQkKCioqIW27jdbqWmpmrSpEnKyMgwsxwAwCNYzFqH4PP5lJiY\n", 406 | "qMrKSsXExCg9PV1lZWWy2+2BNjdu3NCsWbNUUVEhm82ma9euafjw4WaUAwBog2k9hOrqasXHxysu\n", 407 | "Lk5Wq1XZ2dkqLy9v0ubtt9/WkiVLZLPZJIkwAIAQMi0QvF6vYmNjA9s2m01er7dJm3Pnzun69et6\n", 408 | "7rnnlJaWprfeesuscgAAbYg068AWi6XNNvfv31dNTY2OHDmi+vp6zZw5U88884wSEhLMKgsA0ArT\n", 409 | "AiEmJkYejyew7fF4AkNDD8XGxmr48OGKiopSVFSUvv71r+vUqVPNAqE94QIAaK4j08SmDRmlpaXp\n", 410 | "3Llzqqur071797R37145nc4mbb797W/r2LFj8vl8qq+v1wcffKDk5OQWj2cYRti+XnnllZDXwPlx\n", 411 | "bpxf+L06yrQeQmRkpEpKSuRwOOTz+ZSbmyu73a7S0lJJUl5enpKSkjR37lxNmTJFERERWrVqVauB\n", 412 | "AAAwl2mBIEnz5s3TvHnzmnyWl5fXZPull17SSy+9ZGYZAIB2YKVyDxDuC/LC+fzC+dwkzq+3MW1h\n", 413 | "WjBZLJZOjYcBQG/W0e9OeggAAEkEAgDAj0AAAEgiEAAAfgQCAEASgQAA8CMQAACSCAQAgB+BAACQ\n", 414 | "RCAAAPwIBACAJAIBAOBHIAAAJBEIAAA/AgEAIIlAAAD4EQgAAEkEAgDAj0AAAEgiEAAAfgQCAEAS\n", 415 | "gQAA8CMQAACSCAQAgB+BAACQRCAAAPxMDQSXy6WkpCQlJCSoqKio2c/dbreGDBmi1NRUpaam6mc/\n", 416 | "+5mZ5QAAHiHSrAP7fD7l5+ersrJSMTExSk9Pl9PplN1ub9LuG9/4hg4cOGBWGQCAdjKth1BdXa34\n", 417 | "+HjFxcXJarUqOztb5eXlzdoZhmFWCR1WUVGhrKwlyspaooqKilCXAwDdyrRA8Hq9io2NDWzbbDZ5\n", 418 | "vd4mbSwWi44fP66UlBTNnz9ftbW1ZpXTpoqKCi1alKPDh506fNipRYtyCAUAvYppQ0YWi6XNNk8/\n", 419 | "/bQ8Ho/69++vQ4cOaeHChTp79qxZJT1ScfF2NTQUScqRJDU0PPjM4XCEpB4A6G6mBUJMTIw8Hk9g\n", 420 | "2+PxyGazNWkzaNCgwPt58+Zp7dq1un79up566qlmxyssLAy8z8jIUEZGRtBrBoDHmdvtltvt7vT+\n", 421 | "FsOkQfzGxkYlJibqyJEjio6O1vTp01VWVtZkUvnq1asaOXKkLBaLqqur9Z3vfEd1dXXNi7RYTJ9r\n", 422 | "eDhk9KCXIEVFbdC+fbvoIQB4bHX0u9O0HkJkZKRKSkrkcDjk8/mUm5sru92u0tJSSVJeXp5+//vf\n", 423 | "6ze/+Y0iIyPVv39/7dmzx6xy2uRwOLRv3y4VF2+XJBUUEAYAehfTegjB1B09BAAINx397mSlMgBA\n", 424 | "EoEAAPAjEAAAkggEAIAfgQAAkEQgAAD8CAQAgCQCAQDgRyAAACQRCAAAPwIBACCJQAAA+BEIAABJ\n", 425 | "BAIAwI9AAABIIhAAAH4EAgBAEoEAAPAjEAAAkggEAIAfgQAAkEQgAAD8CAQAgCQCAQDgRyAAACQR\n", 426 | "CAAAPwIBACCJQAAA+BEIAABJJgeCy+VSUlKSEhISVFRU1Gq7v/71r4qMjNQf/vAHM8sBADyCaYHg\n", 427 | "8/mUn58vl8ul2tpalZWV6cyZMy2227Bhg+bOnSvDMMwqBwDQBtMCobq6WvHx8YqLi5PValV2drbK\n", 428 | "y8ubtXvttde0dOlSjRgxwqxSAADtYFogeL1excbGBrZtNpu8Xm+zNuXl5VqzZo0kyWKxmFUOAKAN\n", 429 | "kWYduD1f7uvXr9fmzZtlsVhkGMYjh4wKCwsD7zMyMpSRkRGEKgEgfLjdbrnd7k7vbzFMGrivqqpS\n", 430 | "YWGhXC6XJGnTpk2KiIjQhg0bAm3GjRsXCIFr166pf//+ev311+V0OpsW6Q8MAED7dfS707RAaGxs\n", 431 | "VGJioo4cOaLo6GhNnz5dZWVlstvtLbZfsWKFFixYoMWLFzcvkkAAgA7r6HenaUNGkZGRKikpkcPh\n", 432 | "kM/nU25urux2u0pLSyVJeXl5Zv1qAEAnmNZDCCZ6CADQcR397mSlMgBAEoEAAPAjEAAAkggEAIAf\n", 433 | "gQAAkEQgAAD8CAQAgCQCAQDgRyAAACQRCAAAPwIBACCJQAAA+BEIAABJBAIAwI9AAABIesQDciZP\n", 434 | "ntzqThaLRadPnzalIABAaLT6gJy6urpH7hgXF2dCOS3jATkA0HE95pnKwRSugVBRUaHi4u2SpIKC\n", 435 | "1XI4HCGuCEA4CfoT095//32lp6drwIABslqtioiI0ODBg7tUJB6EwaJFOTp82KnDh51atChHFRUV\n", 436 | "oS4LQC/WZiDk5+fr7bff1oQJE3Tnzh3t2LFDa9eu7Y7awlpx8XY1NBRJypGUo4aGokBvAQBCoV1X\n", 437 | "GSUkJMjn86lPnz5asWKFXC6X2XUBALpZq1cZPTRgwADdvXtXKSkp+tGPfqTRo0eH5Xh+dysoWK1j\n", 438 | "x3LU0PBgOypqgwoKdoW2KAC9WpuTyhcvXtTIkSN17949vfrqq7p586bWrl2r+Pj47qqRSWUA6ISg\n", 439 | "XmXU2NionJwc7d69OyjFdVa4BgIAmCmoVxlFRkbq4sWLunv3bpcLAwD0bG3OIYwdO1Zf+9rX5HQ6\n", 440 | "1b9/f0kPUucHP/iB6cUBALpPm4Ewfvx4jR8/Xv/73/9069YtGYYhi8XSHbUBALoRK5UBIEx19Luz\n", 441 | "zR7CggULmhzUYrFoyJAhSktLU15envr169fqvi6XS+vXr5fP59PKlSu1YcOGJj8vLy/XT37yE0VE\n", 442 | "RCgiIkJbtmzR7Nmz2108ACB42uwhrFu3TteuXdPzzz8vwzC0d+9eDR48WBEREbp586beeuutFvfz\n", 443 | "+XxKTExUZWWlYmJilJ6errKyMtnt9kCb27dva8CAAZKkDz/8UIsWLdL58+ebF0kPAQA6LOg9hOPH\n", 444 | "j+vEiROBbafTqbS0NJ04cUITJ05sdb/q6mrFx8cH7oqanZ2t8vLyJoHwMAwk6datWxo+fHi7CwcA\n", 445 | "BFebt664ffu2Ll68GNi+ePGibt++LUl64oknWt3P6/UqNjY2sG2z2eT1epu1279/v+x2u+bNm6dt\n", 446 | "27Z1qHgAQPC02UMoLi7Ws88+q3HjxkmSPvnkE/3617/W7du3lZOT0+p+7b0SaeHChVq4cKGOHj2q\n", 447 | "7373u/rXv/7VYrvCwsLA+4yMDGVkZLTr+ADQW7jdbrnd7k7v366rjO7cuRP4ok5MTHzkRPJDVVVV\n", 448 | "KiwsDNwIb9OmTYqIiGg2sfxF48ePV3V1tYYNG9a0SOYQAKDDgv48hNu3b2vLli0qKSlRSkqKPB6P\n", 449 | "3n333TYPnJaWpnPnzqmurk737t3T3r175XQ6m7T5+OOPA8XW1NRIUrMwAAB0jzaHjFasWKFp06bp\n", 450 | "+PHjkqTo6GgtXbpU3/rWtx594MhIlZSUyOFwyOfzKTc3V3a7XaWlpZKkvLw8vfPOO3rzzTdltVo1\n", 451 | "cOBA7dmzJwinBADojDaHjKZNm6a//e1vSk1N1cmTJyVJKSkpOnXqVLcUKDFkBACdEfQho759+6rh\n", 452 | "4U379WCYp2/fvp2rDgDQY7U5ZFRYWKi5c+fq0qVLWrZsmd577z298cYb3VAaAKA7tesqo2vXrqmq\n", 453 | "qkqSNGPGDI0YMcL0wr6IISMA6LigPiBHkubMmaMjR460+ZmZCAQA6Lig3bqioaFB9fX1+uyzz3T9\n", 454 | "+vXA5zdv3mxxxTEA4PHWaiCUlpZq69atunz5sqZNmxb4fNCgQcrPz++W4gAA3afNIaNt27Zp3bp1\n", 455 | "3VVPixgyAoCOC/ocgvTgjqd1dXVqbGwMfLZ8+fLOVdgJBAIAdFzQb3/9wgsv6JNPPtHUqVPVp0+f\n", 456 | "wOfdGQgAAPO12UOw2+2qra0N6XOU6SEAQMcFfaXypEmT9Omnn3apKABAz9fmkNFnn32m5ORkTZ8+\n", 457 | "PXDLCovFogMHDpheHIKroqJCxcXbJUkFBavlcDhCXBGAnqTNIaPWHrbQnQ+oYcio6yoqKrRoUY4a\n", 458 | "GookSVFRG7Rv3y5CAQhjplxlFGoEQtdlZS3R4cNOSQ+fcrdLmZkH9Mc/vhPKsgCYKGhzCLNmzZIk\n", 459 | "DRw4UIMGDWryGjx4cNcrBQD0KPQQegmGjIDehyEjtIpJZaB3IRAAAJJMWIcAAOgdCAQAgCQCAQDg\n", 460 | "RyAAACQRCAAAPwIBACCJQAAA+BEIAABJBAIAwI9AAABI6oZAcLlcSkpKUkJCgoqKipr9fPfu3UpJ\n", 461 | "SdGUKVM0a9YsnT592uySAAAtMDUQfD6f8vPz5XK5VFtbq7KyMp05c6ZJm3Hjxukvf/mLTp8+rR//\n", 462 | "+MdavXq1mSWhG1VUVCgra4myspaooqIi1OUAaEObj9DsiurqasXHxysuLk6SlJ2drfLyctnt9kCb\n", 463 | "mTNnBt7PmDFDly5dMrMkdJMv32772LEcbrcN9HCm9hC8Xq9iY2MD2zabTV6vt9X2O3bs0Pz5880s\n", 464 | "Cd2kuHi7PwxyJD0Ihoe33gbQM5naQ7BYLO1u++c//1k7d+7Ue++91+LPCwsLA+8zMjK69ZnOAPA4\n", 465 | "cLvdcrvdnd7f1ECIiYmRx+MJbHs8HtlstmbtTp8+rVWrVsnlcunJJ59s8VhfDAT0fAUFq3XsWI4a\n", 466 | "Gh5sR0VtUEHBrtAWBYS5L/+x/NOf/rRD+5v6gJzGxkYlJibqyJEjio6O1vTp01VWVtZkDuHf//63\n", 467 | "Zs+erd/97nd65plnWi6SB+Q8lnhCGxBaPe6JaYcOHdL69evl8/mUm5url19+WaWlpZKkvLw8rVy5\n", 468 | "Uvv27dOYMWMkSVarVdXV1U2LJBAAoMN6XCAEA4EAAB3HIzQBAJ1CIAAAJBEIAAA/AgEAIIlAAAD4\n", 469 | "EQgIC9xID+g6LjvFY+/LN9KLitrAjfQAsQ4BvVBW1hIdPuzUgxvpSdIuZWYe0B//+E4oywJCjnUI\n", 470 | "AIBOMfXmdkB34EZ6QHAwZISwwI30gOaYQwAASGIOAQDQSQQCAEASgQB0CgvhEI6YQwA6iIVweFww\n", 471 | "qQyYjIVweFwwqQwA6BQWpgEdxEI4hCuGjIBOYCEcHgfMIQBhiABCZxAIQJjhqiZ0FoEAhBmuakJn\n", 472 | "cZURAKBTuMoI6OG4qgndhSEj4DHQ3ZPKTGKHB+YQAHQJk9jhg0AA0CVMYoePHjep7HK5lJSUpISE\n", 473 | "BBUVFTX7+T//+U/NnDlT/fr1U3FxsdnlAABaYeqkss/nU35+viorKxUTE6P09HQ5nU7Z7fZAm2HD\n", 474 | "hum1117T/v37zSwFQDsxid17mdpDqK6uVnx8vOLi4mS1WpWdna3y8vImbUaMGKG0tDRZrVYzSwHQ\n", 475 | "Tg6HQ/v2PRgmysw80C3zBzxfomcwtYfg9XoVGxsb2LbZbPrggw/M/JUAgsDhcHTbJPKXJ7GPHcth\n", 476 | "EjtETA0Ei8Vi5uEBhIHi4u3+MHgwid3Q8OAzAqH7mRoIMTEx8ng8gW2PxyObzdapYxUWFgbeZ2Rk\n", 477 | "KCMjo4vVAeitwnWdhdvtltvt7vwBDBPdv3/fGDdunHHhwgXj7t27RkpKilFbW9ti21deecX4xS9+\n", 478 | "0eLPTC4TQAi5XC4jKmqUIb1hSG8YUVGjDJfLFTa/L5Q6+t1p+jqEQ4cOaf369fL5fMrNzdXLL7+s\n", 479 | "0tJSSVJeXp6uXLmi9PR03bx5UxERERo0aJBqa2s1cODAwDFYhwCEt+78i703rbNgYRoAPAKB0Dpu\n", 480 | "bgegV2GdRevoIQDodcJ1UvnLGDICAEjqgfcyAgA8HggEAIAkAgEA4EcgAAAkEQgAAD8CAQAgiUAA\n", 481 | "APgRCAAASQQCAMCPQAAASCIQAAB+BAIAQBKBAADwIxAAAJIIBACAH4EAAJBEIAAA/AgEAIAkAgEA\n", 482 | "4EcgAAAkEQgAAD8CAQAgiUAAAPgRCAAASQQCAMDP1EBwuVxKSkpSQkKCioqKWmyzbt06JSQkKCUl\n", 483 | "RSdPnjSzHADAI5gWCD6fT/n5+XK5XKqtrVVZWZnOnDnTpM3Bgwd1/vx5nTt3Ttu3b9eaNWvMKqdH\n", 484 | "c7vdoS7BVOF8fuF8bhLn19uYFgjV1dWKj49XXFycrFarsrOzVV5e3qTNgQMHlJOTI0maMWOGbty4\n", 485 | "oatXr5pVUo8V7v8ow/n8wvncJM6vtzEtELxer2JjYwPbNptNXq+3zTaXLl0yqyQAwCOYFggWi6Vd\n", 486 | "7QzD6NR+AIAgM0zy/vvvGw6HI7C9ceNGY/PmzU3a5OXlGWVlZYHtxMRE48qVK82OJYkXL168eHXi\n", 487 | "1RGRMklaWprOnTunuro6RUdHa+/evSorK2vSxul0qqSkRNnZ2aqqqtLQoUM1atSoZscyvtSLAAAE\n", 488 | "n2mBEBkZqZKSEjkcDvl8PuXm5sput6u0tFSSlJeXp/nz5+vgwYOKj4/XgAED9Nvf/tascgAAbbAY\n", 489 | "/PkNAFAPX6ncnoVtjyuPx6PnnntOEydO1KRJk7Rt27ZQl2QKn8+n1NRULViwINSlBN2NGze0dOlS\n", 490 | "2e12JScnq6qqKtQlBdWmTZs0ceJETZ48WcuWLdPdu3dDXVKXvPjiixo1apQmT54c+Oz69evKzMzU\n", 491 | "hAkTlJWVpRs3boSwws5r6dx++MMfym63KyUlRYsXL9bnn3/e5nF6bCC0Z2Hb48xqterVV1/VRx99\n", 492 | "pKqqKv3qV78Kq/N7aOvWrUpOTg7Lq8e+973vaf78+Tpz5oxOnz4tu90e6pKCpq6uTq+//rpqamr0\n", 493 | "4Ycfyufzac+ePaEuq0tWrFghl8vV5LPNmzcrMzNTZ8+e1Zw5c7R58+YQVdc1LZ1bVlaWPvroI506\n", 494 | "dUoTJkzQpk2b2jxOjw2E9ixse5yNHj1aU6dOlSQNHDhQdrtdly9fDnFVwXXp0iUdPHhQK1euDLsL\n", 495 | "Az7//HMdPXpUL774oqQHc2ZDhgwJcVXBM3jwYFmtVtXX16uxsVH19fWKiYkJdVld8uyzz+rJJ59s\n", 496 | "8tkXF8fm5ORo//79oSity1o6t8zMTEVEPPiKnzFjRrvWePXYQGjPwrZwUVdXp5MnT2rGjBmhLiWo\n", 497 | "vv/972vLli2Bf5Th5MKFCxoxYoRWrFihp59+WqtWrVJ9fX2oywqap556SgUFBRozZoyio6M1dOhQ\n", 498 | "ffOb3wx1WUF39erVwJWNo0aNCts7JezcuVPz589vs12P/Z8ajkMMLbl165aWLl2qrVu3auDAgaEu\n", 499 | "J2jeffddjRw5UqmpqWHXO5CkxsZG1dTUaO3ataqpqdGAAQMe2+GGlnz88cf65S9/qbq6Ol2+fFm3\n", 500 | "bt3S7t27Q12WqSwWS1h+7/z85z/XE088oWXLlrXZtscGQkxMjDweT2Db4/HIZrOFsKLgu3//vpYs\n", 501 | "WaIXXnhBCxcuDHU5QXX8+HEdOHBAY8eO1fPPP68//elPWr58eajLChqbzSabzab09HRJ0tKlS1VT\n", 502 | "UxPiqoLnxIkT+upXv6phw4YpMjJSixcv1vHjx0NdVtCNGjVKV65ckSR9+umnGjlyZIgrCq433nhD\n", 503 | "Bw8ebHeY99hA+OLCtnv37mnv3r1yOp2hLitoDMNQbm6ukpOTtX79+lCXE3QbN26Ux+PRhQsXtGfP\n", 504 | "Hs2ePVtvvvlmqMsKmtGjRys2NlZnz56VJFVWVmrixIkhrip4kpKSVFVVpYaGBhmGocrKSiUnJ4e6\n", 505 | "rKBzOp3atWuXJGnXrl1h9YeZy+XSli1bVF5ern79+rVvpw6ta+5mBw8eNCZMmGCMHz/e2LhxY6jL\n", 506 | "CaqjR48aFovFSElJMaZOnWpMnTrVOHToUKjLMoXb7TYWLFgQ6jKC7u9//7uRlpZmTJkyxVi0aJFx\n", 507 | "48aNUJcUVEVFRUZycrIxadIkY/ny5ca9e/dCXVKXZGdnG1/5ylcMq9Vq2Gw2Y+fOncZ//vMfY86c\n", 508 | "OUZCQoKRmZlp/Pe//w11mZ3y5XPbsWOHER8fb4wZMybw/bJmzZo2j8PCNACApB48ZAQA6F4EAgBA\n", 509 | "EoEAAPAjEAAAkggEAIAfgQAAkEQgAAD8CAQAgCQCAeiUuro62e12rV69WpMmTZLD4dCdO3dCXRbQ\n", 510 | "JQQC0Ennz59Xfn6+/vGPf2jo0KF65513Ql0S0CUEAtBJY8eO1ZQpUyRJ06ZNU11dXWgLArqIQAA6\n", 511 | "qW/fvoH3ffr0UWNjYwirAbqOQAAASCIQgE778tO1wvFpW+hduP01AEASPQQAgB+BAACQRCAAAPwI\n", 512 | "BACAJAIBAOBHIAAAJBEIAAA/AgEAIEn6P8bCIpYjHAxmAAAAAElFTkSuQmCC\n" 513 | ], 514 | "text/plain": [ 515 | "" 516 | ] 517 | }, 518 | "metadata": {}, 519 | "output_type": "display_data" 520 | } 521 | ], 522 | "source": [ 523 | "def intgrnd2(x, n):\n", 524 | " return x**n\n", 525 | "\n", 526 | "def intgrl2(m): # make the parameter a variable\n", 527 | " return quad(intgrnd2, 0.0, 1.0, args=(m))\n", 528 | "\n", 529 | "vec_intgrl2 = vectorize(intgrl2)\n", 530 | "\n", 531 | "nlist = linspace(1, 10, 10)\n", 532 | "results, errs = vec_intgrl2(nlist)\n", 533 | "\n", 534 | "figure() # opens a new figure\n", 535 | "scatter(nlist, results)\n", 536 | "xlabel('n')\n", 537 | "ylabel('integral')\n", 538 | "show()" 539 | ] 540 | }, 541 | { 542 | "cell_type": "markdown", 543 | "metadata": {}, 544 | "source": [ 545 | "## Exercise" 546 | ] 547 | }, 548 | { 549 | "cell_type": "markdown", 550 | "metadata": {}, 551 | "source": [ 552 | "The electric field a distance z above the center of a segment of length 2L with uniform\n", 553 | "charge per length λ is vertical and its magnitude is\n", 554 | "$$ E(z) = \\frac{\\lambda z}{4\\pi\\epsilon_0} \\int_{-L}^L \\frac{dx^\\prime}{(x^{\\prime 2}+z^2)^{3/2}}$$.\n", 555 | "
    \n", 556 | "
  1. If you aren't give the values of all of the variables (L and λ in this case), it is best\n", 557 | "to work with quantities that don't have units. Find an expression (integral) for the unitless quantity\n", 558 | "EL/kλ, where k =1/4πε0.\n", 559 | "
  2. Plot EL/kλ vs. Z/L for values of Z/L from 0.5 to 10.0. (Have the computer solve the integral numerically!\n", 560 | "
" 561 | ] 562 | }, 563 | { 564 | "cell_type": "markdown", 565 | "metadata": {}, 566 | "source": [] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "metadata": {}, 571 | "source": [] 572 | }, 573 | { 574 | "cell_type": "code", 575 | "execution_count": null, 576 | "metadata": { 577 | "collapsed": false 578 | }, 579 | "outputs": [], 580 | "source": [] 581 | } 582 | ], 583 | "metadata": { 584 | "kernelspec": { 585 | "display_name": "Python 2", 586 | "language": "python", 587 | "name": "python2" 588 | }, 589 | "language_info": { 590 | "codemirror_mode": { 591 | "name": "ipython", 592 | "version": 2 593 | }, 594 | "file_extension": ".py", 595 | "mimetype": "text/x-python", 596 | "name": "python", 597 | "nbconvert_exporter": "python", 598 | "pygments_lexer": "ipython2", 599 | "version": "2.7.9" 600 | } 601 | }, 602 | "nbformat": 4, 603 | "nbformat_minor": 0 604 | } 605 | --------------------------------------------------------------------------------