def main(): toSort = list(range(0, 21)) fyShuffle(toSort) bubbleSort(toSort) fyShuffle(toSort) insertionSort(toSort) fyShuffle(toSort) mergeSort(toSort) fyShuffle(toSort) quickSort(toSort) fyShuffle(toSort) selectionSort(toSort) toSearch = [-16, -8, -4, -2, -1, 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096] for i in range (0, len(toSearch)): binarySearch(toSearch, toSearch[i] - 1) binarySearch(toSearch, toSearch[i]) binarySearch(toSearch, toSearch[i] + 1) for i in range (0, len(toSearch)): interpolationSearch(toSearch, toSearch[i] - 1) interpolationSearch(toSearch, toSearch[i]) interpolationSearch(toSearch, toSearch[i] + 1) toSearch = [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10] for i in range (0, len(toSearch)): binarySearch(toSearch, toSearch[i] - 1) binarySearch(toSearch, toSearch[i]) for i in range (0, len(toSearch)): interpolationSearch(toSearch, toSearch[i] - 1) interpolationSearch(toSearch, toSearch[i])
def testBinarySearch(): from binarySearch import binarySearch list = [1, 3, 5, 7, 9] print(binarySearch(list, 5)) print(binarySearch(list, 50)) print(binarySearch(list, 9)) print(binarySearch(list, 1))
def rotateFinding(seq, num): lo = 0 hi = len(seq) - 1 pivot = findPivot(seq, lo, hi) if pivot == -1: return binarySearch(seq, lo, hi, num) elif seq[pivot] == num: return pivot elif seq[0] < num: return binarySearch(seq, lo, pivot, num) return binarySearch(seq, pivot + 1, hi, num)
def __init__(self, probability_distribution_on_path): self.base_probability_distribution = pd.ProbabilityDistribution() self.base_probability_distribution.distribution = probability_distribution_on_path.params_of_product_distribution_sharing_marginals() self.t_max = self.t_max() self.t_min = self.t_min() #for situations where it is convenient to mark a special p_eta as the base for calculating KL-divergnece: self.markedProbabilityDist = None self.binarySearchOnKLDivergence = bS.binarySearch( tolerance_exp=10,maxDepth=500,increasingFunction=self.KL_divergence_at_t) self.binarySearchOnMinusKLDivergence = bS.binarySearch( tolerance_exp=10,maxDepth=500,increasingFunction= self.minus_KL_divergence_at_t)
def testBinarySearch1(self): arr = [ [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], ] target = [ 1, 3, 5, 9, 0 ] expected = [ 0, 2, 4, None, None, ] for i in range(5): result = binarySearch(arr[i], 0, len(arr[i])-1, target[i]) self.assertIsNone self.assertEqual(result, expected[i])
def specialFactors(f, p): m = f[-1] max_val = int(p / f[1]) x = binarySearch.binarySearch(f, max_val) + 1 result = set(pse for pse in specialIterator(f[1:x], p) if pse < p) result.add(1) return sorted(result)
def __init__(self, probability_distribution_on_path): self.base_probability_distribution = pd.ProbabilityDistribution() self.base_probability_distribution.distribution = probability_distribution_on_path.params_of_product_distribution_sharing_marginals( ) self.t_max = self.t_max() self.t_min = self.t_min() #for situations where it is convenient to mark a special p_eta as the base for calculating KL-divergnece: self.markedProbabilityDist = None self.binarySearchOnKLDivergence = bS.binarySearch( tolerance_exp=10, maxDepth=500, increasingFunction=self.KL_divergence_at_t) self.binarySearchOnMinusKLDivergence = bS.binarySearch( tolerance_exp=10, maxDepth=500, increasingFunction=self.minus_KL_divergence_at_t)
def search_button_command(*args): try: key = current_component_list_box_key bag_of_parts = permuted_components[key] # get the sought after value from component_search_entry text = search_entry_var.get() val = 0.0 try: val = float(text) obj_indx = binarySearch.binarySearch(bag_of_parts, val) obj = bag_of_parts[obj_indx] status_label_var.set("found a component: " + str(obj.getValue())) r_frame.draw_resistors(obj.getParts()) # clear all the current idecies highlighted = browse_all_list_box.curselection() for item in highlighted: browse_all_list_box.selection_clear(item) # highlight the index that the binary search # returned _ browse_all_list_box.selection_set(obj_indx) browse_all_list_box.see(obj_indx) print(obj) except ValueError: status_label_var.set("Search entry contents not valid") return except Exception as e: print(e) return
def specialFactors(f, p) : m = f[-1] max_val = int(p / f[1]) x = binarySearch.binarySearch(f, max_val) + 1 result = set(pse for pse in specialIterator(f[1:x], p) if pse < p ) result.add(1) return sorted(result)
def countOccurInSortedArr(seq, num): result = [] start = 0 end = len(seq)-1 pos = binarySearch(seq, start, end, num) if pos >= 0: j = 0 i = 0 pos1 = pos2 = pos while pos1 >= 0: i = pos1 pos1 = binarySearch(seq, start, pos1-1, num) while pos2 >0 and pos2 <= end: j = pos2 pos2 = binarySearch(seq, pos2+1, end, num) return j - i +1 return 0
def euler51(lower_limit) : import binarySearch upper_limit = 10 * lower_limit p = primes.primes(upper_limit + 50) lower = binarySearch.binarySearch(p, lower_limit) upper = binarySearch.binarySearch(p, upper_limit) minimum = 7 for i in xrange(lower, upper) : pi = p[i] print >> sys.stderr, pi, "\r", for x in test(pi) : if testPrimes(x, lower_limit, minimum) : print pi, x if len(x) == 8 : sys.exit(0) p = None
def euler51(lower_limit): import binarySearch upper_limit = 10 * lower_limit p = primes.primes(upper_limit + 50) lower = binarySearch.binarySearch(p, lower_limit) upper = binarySearch.binarySearch(p, upper_limit) minimum = 7 for i in xrange(lower, upper): pi = p[i] print >> sys.stderr, pi, "\r", for x in test(pi): if testPrimes(x, lower_limit, minimum): print pi, x if len(x) == 8: sys.exit(0) p = None
def threesum(threesum_array): length = len(threesum_array) count = 0 for i in range(length): for j in range(i + 1, length): idx = binarySearch.binarySearch(threesum_array[j + 1:], -(threesum_array[i] + threesum_array[j])) if idx != -1: count += 1 print "%d matches were found" % count;
def testInOrder(): arr = [] print("\nRunning testInOrder:") # Insert elements in order for i in range(ELEMENTS): arr.append(i) # Ensure we can find every element for i in range(ELEMENTS): assert (binarySearch(arr, i) != -1) print("***** PASS *****")
class App(object): print "Your array is: 2, 3, 4, 10, 40" array = [ 2, 3, 4, 10, 40 ] x = input("Please, insert the element thar you can search: ") result = binarySearch(array, 0, len(array)-1, x) if result != -1: print "Element is present at index %d ;)" % result else: print "Element is not present in array :("
def getTemperature(): date = input("\nEnter the date here: ") while date != "DONE": found = False found, i = binarySearch(daysList2, eval(date)) if found: print("The temperature for", date, "in fahrenheit degrees was; Max: ", fahrConverter(daysList2[i].getMaxTemp()), ", min:", fahrConverter(daysList2[i].getMinTemp())) found = True else: print("The temperature for that day is not in the record") date = input("\nEnter the date here: ")
def sort(arr,element): count = 0 array = arr.copy() n = len(array) array = mergeSort(array) for i in range(n): second_integer = element - array[i] second_integer_index, frequency = binarySearch(array[i+1:],second_integer,1) if second_integer_index != -1: count += frequency #for _ in range(frequency): # print(f"({array[i]},{second_integer})", end = " ") #print(end = "\n") return count
def t_at_specifiedDivergenceFromMarkedDistInDirectionOfBase( self, specifiedDivergence): """ This only looks in the direction of negative t from the marked distribution to find a distribution of the specified KL-divergence from the "marked distribution" with the marked distribution as base. The method supposes that the marked distribution is in the positive-t direction from the base: See the testProbabilityDistributionPath. test_t_atSpecified_KL_DivergenceFromMarkedDistribution for more documentation (through the test) """ if not self.markedProbabilityDist: raise ValueError("No marked distribution.") upper_limit = self.tOfMarkedDistribution() lower_limit = 0 #KL_divergence_at_upper_limit = KL(p^0 \| p^\eta) KL_divergence_at_upper_limit = self.markedProbabilityDist.\ KL_divergence_as_base( #KL(\cdot \| p^\eta) self.distribution_at_t_as_distribution( self.tOfMarkedDistribution() - upper_limit #0 ).distribution) #p^0 if (specifiedDivergence > KL_divergence_at_upper_limit): raise ValueError( "Specified divergence " + str(specifiedDivergence) + " is greater than KL_divergence of uniform dist based at p^\eta = " + str(KL_divergence_at_upper_limit)) increasingFunct = lambda t : self.markedProbabilityDist.\ KL_divergence_as_base( #KL(\cdot \| p^\eta) self.distribution_at_t_as_distribution( self.tOfMarkedDistribution() - t # t_eta^+ - t ).distribution) #p(t_\eta^+ - t) self.binarySearchOnKLDivFromMarkedDistribution = bS.binarySearch( tolerance_exp=15, maxDepth=500, increasingFunction=increasingFunct) s = self.binarySearchOnKLDivFromMarkedDistribution.search( lower_limit, upper_limit, specifiedDivergence) return self.tOfMarkedDistribution() - s
def t_at_specifiedDivergenceFromMarkedDistInDirectionOfBase(self, specifiedDivergence): """ This only looks in the direction of negative t from the marked distribution to find a distribution of the specified KL-divergence from the "marked distribution" with the marked distribution as base. The method supposes that the marked distribution is in the positive-t direction from the base: See the testProbabilityDistributionPath. test_t_atSpecified_KL_DivergenceFromMarkedDistribution for more documentation (through the test) """ if not self.markedProbabilityDist: raise ValueError("No marked distribution.") upper_limit = self.tOfMarkedDistribution() lower_limit = 0 #KL_divergence_at_upper_limit = KL(p^0 \| p^\eta) KL_divergence_at_upper_limit = self.markedProbabilityDist.\ KL_divergence_as_base( #KL(\cdot \| p^\eta) self.distribution_at_t_as_distribution( self.tOfMarkedDistribution() - upper_limit #0 ).distribution) #p^0 if (specifiedDivergence > KL_divergence_at_upper_limit): raise ValueError("Specified divergence " + str(specifiedDivergence) + " is greater than KL_divergence of uniform dist based at p^\eta = " + str(KL_divergence_at_upper_limit)) increasingFunct = lambda t : self.markedProbabilityDist.\ KL_divergence_as_base( #KL(\cdot \| p^\eta) self.distribution_at_t_as_distribution( self.tOfMarkedDistribution() - t # t_eta^+ - t ).distribution) #p(t_\eta^+ - t) self.binarySearchOnKLDivFromMarkedDistribution = bS.binarySearch( tolerance_exp=15,maxDepth=500,increasingFunction=increasingFunct) s = self.binarySearchOnKLDivFromMarkedDistribution.search( lower_limit,upper_limit,specifiedDivergence) return self.tOfMarkedDistribution() - s
def testRandom(): arr = [] # Range for random integers low, high = 0, 1000 print("\nRunning testRandom:") # Insert random elements for _ in range(ELEMENTS): arr.append(randint(low, high)) # Sort array quicksort(arr) # Ensure we can find all the elements in the array for num in arr: if (binarySearch(arr, num) == -1): print("Error: number {} not found in array".format(\ num)) #assert(binarySearch(arr, num) != -1) print("***** PASS *****")
def component_search(*args): try: key = get_key_from_component_list_box() #print(key) #print_permuted_components_with_key(permuted_components, key) bag_of_parts = permuted_components[key] #get the value from component_search_entry text = component_search_entry_var.get() val = 0.0 try: val = float(text) obj = binarySearch.binarySearch(bag_of_parts, val) print('found: ', obj) status_label_var.set(str(obj)) except ValueError: status_label_var.set('Search entry contents not valid') return except Exception as e: print(e) return
def testNonInterval(self): newBinarySearchObject = bS.binarySearch(tolerance_exp=7, maxDepth=1000, increasingFunction=math.sqrt) newBinarySearchObject.search(9,1,2,0)
def test_case_3(self): self.assertEqual(binarySearch([-5,-1,11,23,111], 11),2)
def testNonIncreasingFunction(self): def f(posReal): return -math.sqrt(posReal) newBinarySearchObject = bS.binarySearch(tolerance_exp=7, maxDepth=500, increasingFunction=f) newBinarySearchObject.search(1,9,2,0)
def testCatchingNoFunct(self): newBinarySearchObject = bS.binarySearch(tolerance_exp=7, maxDepth=1000) newBinarySearchObject.search(1,9,2,0)
def test_case_1(self): self.assertEqual(binarySearch([1, 2, 3, 4, 5, 6], 4), 3)
def test_normalRandomEvenInputListPresent(self): for i in range(10): self.assertEqual( True, binarySearch.binarySearch(list(range(1, 101)), random.randint(1, 100)))
def test_normalOddInputListPresent(self): self.assertEqual(True, binarySearch.binarySearch([0, 1, 2, 3, 4], 0))
def testMaxDepth(self): newBinarySearchObject = bS.binarySearch(tolerance_exp=7, maxDepth=500, increasingFunction=math.sqrt) self.failUnlessAlmostEqual(newBinarySearchObject.search(0,1,2,0),1,200)
def test_normalSingletonInputListPresent(self): self.assertEqual(True, binarySearch.binarySearch([1], 1))
# timeBinarySearch.py """Times the iterative binary search repeatedly""" from time import perf_counter from binarySearch import binarySearch testSize = 10000 # Number of items to search consisting of evenList = list(range(0, 2*testSize, 2)) # even numbers from 0 to 2*(testSize-1) start = perf_counter() for target in range(2*testSize): binarySearch(target, evenList) # end for end = perf_counter() runTime = end - start print( "Time to run Iterative BinarySearch to locate targets 0 to %d is %.4f sec." % \ (2*testSize - 1, runTime))
from binarySearch import binarySearch file = open('../random-numbers.txt') array = [] for val in file.read().split(): array.append(int(val)) print (binarySearch(array, 4204, 0, len(array))) # 0 print (binarySearch(array, 2125353, 0, len(array))) # 201 print (binarySearch(array, 7638830, 0, len(array))) # 779 print (binarySearch(array, 9760609, 0, len(array))) # 1000 print (binarySearch(array, 9760608, 0, len(array))) # -1
def test_case_3(self): self.assertEqual(binarySearch([1, 2, 3, 4, 5, 6], 11), None)
def test_normalEmptyInputList(self): self.assertEqual(False, binarySearch.binarySearch([], 1))
def test_case_2(self): self.assertEqual(binarySearch([1, 2, 3, 4, 5, 6], 6), 5)
def test_normalSingletonInputListAbsent(self): self.assertEqual(False, binarySearch.binarySearch([0], 1))
def testSqrtBinarySearch(self): newBinarySearchObject = bS.binarySearch(tolerance_exp=7,maxDepth = 10000, increasingFunction=math.sqrt) x_hat = newBinarySearchObject.search(1,9,2,0) self.assertAlmostEqual(x_hat,4,7)
def test_case_4(self): self.assertEqual(binarySearch([-5,-1,11,23,33,56,112], 112),6)
from binarySearch import binarySearch testarr1 = [i for i in xrange(101)] for testfind1 in xrange(len(testarr1)+1): result = binarySearch(testarr1, testfind1) print (testfind1, result) print "Testing if its multiplied by 2" testarr2 = [testitem*2 for testitem in testarr1] armin = min(testarr2) armax = max(testarr2) print testarr2 print (armin, armax) print "-"*10 for testfind2 in xrange(armin - 1, armax + 2): result = binarySearch(testarr2, testfind2) print (testfind2, result)
def test_case_1(self): self.assertEqual(binarySearch([1,5,23,111], 111),3)
def test_normalEvenInputListAbsent(self): self.assertEqual(False, binarySearch.binarySearch([0, 1, 2, 3], 4))
def test_case_2(self): self.assertEqual(binarySearch([1,5,23,111], 101),-1)
def test_case2(self): test1 = [0,1,2,3,4,5,6,7,8] self.assertEqual(binarySearch(test1, 6) ,6)
def test_normalOddInputListAbsent(self): self.assertEqual(False, binarySearch.binarySearch([0, 1, 2, 3, 4], 5))