def test_search_algorithms():
    ''' Times the execution of the three search functions '''
    
    import time
    the_list = range(1000000)

    # --- Run and time linear search implemented with a for loop --- #
    t1 = time.clock()
    index = search.linear_search_for(the_list, 750000)
    t2 = time.clock()
    
    # Convert from seconds to milliseconds
    exec_time = (t2-t1)*1000
    print "Linear search: %.4f ms (with for loop)" % exec_time
    print "Element found in index %d" % index

    # --- Run and time linear search implemented with a while loop --- #
    t1 = time.clock()
    index = search.linear_search_while(the_list, 750000)
    t2 = time.clock()
    
    # Convert from seconds to milliseconds
    exec_time = (t2-t1)*1000
    print "\nLinear search: %.4f ms (with while loop)" % exec_time
    print "Element found in index %d" % index

    # --- Run and time binary search --- #
    t1 = time.clock()
    index = search.binary_search(the_list, 750000)
    t2 = time.clock()
    
    # Convert from seconds to milliseconds
    exec_time = (t2-t1)*1000
    print "\nBinary search: %.4f ms" % exec_time
    print "Element found in index %d" % index
def test_binary_search():
    assert_equal(binary_search([1, 2, 3], 2), 1)
    assert_equal(binary_search([1, 5, 7, 8, 16, 34, 35], 34), 5)
    assert_equal(binary_search([23, 24, 25, 55, 67, 89], 23), 0)
    assert_equal(binary_search([23, 24, 25, 55, 67, 89], 89), 5)
    assert_equal(binary_search([23, 24, 25, 55, 67, 89], 57), -1)
    assert_equal(binary_search([], 57), -1)
    assert_equal(binary_search(None, 57), -1)
示例#3
0
文件: main.py 项目: h2oboi89/Euler
def main():
    limit = 1000000

    prime_numbers = primes(limit)

    prime_sums = [0]

    for prime_number in prime_numbers:
        prime_sum = prime_sums[-1] + prime_number

        if prime_sum < limit:
            prime_sums.append(prime_sum)
        else:
            break

    chain_length = -1
    result = -1

    for prime_sum in prime_sums[::-1]:
        index_adjustment = 0
        index = binary_search(prime_sums, prime_sum)

        for prime_number in prime_numbers:
            if binary_search(prime_numbers, prime_sum) != -1:
                current_chain_length = index - index_adjustment

                if current_chain_length > chain_length:
                    chain_length = current_chain_length
                    result = prime_sum

                if current_chain_length < chain_length:
                    break
            else:
                prime_sum = prime_sum - prime_number

                index_adjustment += 1

                if prime_sum < 0 or index - index_adjustment < chain_length:
                    break

    return result
示例#4
0
 def test_binary_search_with_items_in_list(self):
     # binary search requires list values to be in sorted order
     names = ['Winnie', 'Alex', 'Nick', 'Brian', 'Julia', 'Kojin', 'Nabil']
     # binary search should return the index of each item in the list
     assert binary_search(names, 'Alex') == 0
     assert binary_search(names, 'Brian') == 1
     assert binary_search(names, 'Julia') == 2
     assert binary_search(names, 'Kojin') == 3
     assert binary_search(names, 'Nabil') == 4
     assert binary_search(names, 'Nick') == 5
     assert binary_search(names, 'Winnie') == 6
示例#5
0
def test_binary_search():
    """Binary search on sequences of different types"""
    arr = [1, 3, 5, 7]
    assert binary_search(arr, 7) == 7
    assert binary_search(arr, 1) == 1
    assert binary_search(arr, 100) is None

    arr1 = [1, 10]
    assert binary_search(arr1, 1) == 1
    assert binary_search(arr1, 10) == 10

    arr2 = ["a", "b", "c", "d", "e"]
    assert binary_search(arr2, "a") == "a"
    assert binary_search(arr2, "e") == "e"
    assert binary_search(arr2, "b") == "b"
示例#6
0
    def test_search(self):
        # Set up array to search
        array_len = 1024
        max_value = 1024

        # With duplicate values (needs stable binary search)
        #x = sorted([random.randint(0, max_value) for i in range(array_len)])

        # Without duplicate values (doesn't need stable binary search)
        x = range(max_value + 1)
        
        # Pick a random value to search for
        v = random.choice(x[1:-1])
        idx = x.index(v)

        # Binary search
        # --- value found
        self.assertEqual(search.binary_search(x, v), idx)
        # (Edge cases)
        self.assertEqual(search.binary_search(x, x[0]), 0)
        self.assertEqual(search.binary_search(x, x[array_len - 1]), array_len - 1)
        # --- value not found
        self.assertEqual(search.binary_search(x, max_value + 1), -1)
示例#7
0
 def worstCaseBinarySearch(self):
     self.clearData()
     items = 1000000
     while items <= self.max_:
         data = random.sample(range(self.max_), items)
         data.sort()
         start = time()
         index = binary_search(data, data[len(data) - 1])
         end = time()
         elapsed = end - start
         print(f"Elapsed Time for {items} datas: {elapsed}")
         self.plotdatas.append((items, elapsed))
         items = int(items * 1.5)
     self.displayData("Worst case of Binary Search", 'blue')
 def find_course(self, to_add):     #O(log(n))
     #Creates a list of course "ids"
     li = [x.title + x.dept + str(x.number) for x in self.course_list]
     #Creates id for thing to look for
     item = to_add.title + to_add.dept + str(to_add.number)
     #print(li, item)
     #Search
     #This has O(log(n)) complexity
     x = search.binary_search(sorter.mergesort(li), \
             len(li)//2, len(li), 0, item)
     if x:
         return to_add
     else:
         print("Attempted to add a course not in the master list")
         return None
示例#9
0
 def test_binary_search_with_items_not_in_list(self):
     # binary search requires list values to be in sorted order
     names = [
         'Alex', 'Brian', 'Julia', 'Kojin', 'Nabil', 'Nick', 'Winnie',
         'Zack'
     ]
     # binary search should return None for any item not in the list
     assert binary_search(names, 'Jeremy') is None
     assert binary_search(names, 'nobody') is None
     assert binary_search(names, 'Aardvark') is None
     assert binary_search(names, 'Kai') is None
     assert binary_search(names, 'Mark') is None
     assert binary_search(names, 'Sam') is None
示例#10
0
def test_search_at_end():
    gen = make_data()
    data = next(gen)

    start = time.perf_counter()
    result = binary_search(data, data[-1])
    fastest = time.perf_counter() - start
    assert result

    start = time.perf_counter()
    result = linear_search(data, data[-1])
    slowest = time.perf_counter() - start
    assert result
    assert fastest * 10000 < slowest * 10000

    start = time.perf_counter()
    result = jump_search(data, data[-1])
    fastest = time.perf_counter() - start
    assert result
    assert fastest * 10000 < slowest * 10000
示例#11
0
def generateForBinary():
    binary_result = {
        "input_array": [],
        "exec_best": [],
        "exec_worst": [],
        "exec_avg": [],
    }
    dataset = range(100000)
    for i in range(10, 100000, 250):
        data = sorted(sample(dataset, i))
        binary_result["input_array"].append(i)
        dataMiddle = data[(i - 1) // 2]
        start = time()
        # best case
        binary_search(data, dataMiddle, 0, i - 1)
        elapsed = time() - start
        binary_result["exec_best"].append(elapsed)
        start = time()
        # worst case
        binary_search(data, -1, 0, i - 1)
        elapsed = time() - start
        binary_result["exec_worst"].append(elapsed)
        random = choice(data)
        start = time()
        binary_search(data, random, 0, i - 1)
        elapsed = time() - start
        binary_result["exec_avg"].append(elapsed)
    df = pd.DataFrame.from_dict(binary_result)
    df.to_csv('binary_data.csv', index=False)
    plt.figure(1, figsize=(14, 12))
    plt.title("Input size vs Exec time")
    plt.xlabel('Input size')
    plt.ylabel('Exec time')
    plt.plot(binary_result["input_array"],
             binary_result["exec_best"],
             c='green',
             label="Best case")
    plt.plot(binary_result["input_array"],
             binary_result["exec_worst"],
             c='red',
             label="Worst case")
    plt.plot(binary_result["input_array"],
             binary_result["exec_avg"],
             c='blue',
             label="Avg case")
    plt.legend()
    plt.show()
示例#12
0
def main():

    name = sys.argv[1];

    for i in xrange(1, 11):
        fname = '../data/%d_catalog.txt' % i
        #read the catalog and load to a list
        phonebook = []
        append = phonebook.append

        with open(fname, 'r') as f:
            for l in f:
                if l:
                    append(Entry.fromline(l))

        #print 'phonebook contains %d entries' % len(phonebook)
        name_idx = BinarySearchTree()
        for i, e in enumerate(phonebook):
            name_idx.add(e.name, i)

        start = time.time()
        idxs = name_idx.get(name)
        bstelapsed = (time.time() - start) * 1000

        # let's sort the entries by name
        phonebook.sort(key=lambda e: e.name)

        # let' search for a non existing name using naive search
        start = time.time()
        idx = search.naive(phonebook, name)
        nelapsed = (time.time() - start) * 1000

        # the same using binary search
        bstart = time.time()
        idx = search.binary_search(phonebook, name)
        bselapsed = (time.time() - bstart) * 1000
        print '%d - naive: %g - binary: %g - bst: %g'\
              % (len(phonebook), nelapsed, bselapsed, bstelapsed)
示例#13
0
def test_binary_search():
    alist = range(10)

    assert search.binary_search(alist, 5)
    assert not search.binary_search(alist, 11)
示例#14
0
 def test_search_player_found(self):
     result = binary_search(self.players, self.player1)
     self.assertEqual(result, 0)
示例#15
0
 def test_not_found(self):
     self.assertEqual(binary_search(self.data, 35), None)
 def test_search_not_found(self):
     result = binary_search(self.test_players, 'Jack')
     self.assertEqual(result, None)
示例#17
0
 def test_binary_search_empty(self):
     self.assertEqual(binary_search([], 0), -1)
示例#18
0
 def test_smaller(self):
     self.assertEqual(binary_search(self.data, 1000), None)
示例#19
0
 def test_searchChar(self):
     data = ['t', 'a', 'b', 'l', 'e', 'c', 'h', 'i', 'r']
     self.assertEqual(binary_search(data, 0, len(data)-1, 'a'), 1)
 def test_binary_search(self):
     self.assertEqual(binary_search(self.list_in1, self.item2), None)
     self.assertEqual(binary_search(self.list_in1, self.item3), None)
     self.assertEqual(binary_search(self.list_in2, self.item1), 0)
     self.assertEqual(binary_search(self.list_in3, self.item1), 0)
 def test_binary_search(self):
     """Test Binary Search method."""
     test = sorted([1, 2, 32, 8, 17, 19, 42, 13, 0])
     self.assertFalse(binary_search([], 1))
     self.assertTrue(binary_search(test, 13))
     self.assertFalse(binary_search(test, 3))
 def test_searchChar(self):
     data = ['a', 'b', 'e', 'l', 't']
     self.assertEqual(binary_search(data, 'a'), 0)
     self.assertEqual(linear_search(data, 'u'), -1)
示例#23
0
 def test_binary_search_with_none_list(self):
     names = None
     assert binary_search(names, 'Trap') is None
示例#24
0
from search import binary_search

elements = [1, 5, 7, 8, 9, 10, 11, 12, 13]

print(binary_search(12, elements))
print(binary_search(78, elements))
示例#25
0
 def test_binary_search_non_empty(self):
     for i in range(1, 5):
         key = i - 1
         self.assertEqual(binary_search(range(i), key), key)
def test_binary_search_find_23():
    assert (binary_search(data.good_data, 23) == 23)
 def test_search_found(self):
     result = binary_search(self.test_players, 'Petersen')
     self.assertEqual(result, self.player4)
def test_binary_search_find_777():
    assert (binary_search(data.good_data, 777) is None)
示例#29
0
 def test_larger(self):
     self.assertEqual(binary_search(self.data, -10), None)
示例#30
0
 def test_search(self):
     data = [1, 2, 3, 5, 6, 12, 7, 4, 8]
     self.assertEqual(binary_search(data, 0, len(data)-1, 6), 4)
     self.assertEqual(binary_search(data, 0, len(data)-1, 10),  -1)
示例#31
0
    def test_binary_search_not_found(self):
        values = [1, 2, 3, 4, 5]

        self.assertEqual(binary_search(values, -1), -1)
示例#32
0
 def test_search(self):
     for i, v in enumerate(self.data):
         with self.subTest(i=i):
             self.assertEqual(binary_search(self.data, v), i)
import random
from search import binary_search
from datetime import datetime

data = random.sample(range(10000000), 1000000)
data = sorted(data)
middle = data[(len(data) - 1) // 2]
binaryStartBest = datetime.now()
binaryIndexBest = binary_search(data, 0, len(data) - 1, middle)
binaryEndBest = datetime.now()
binaryTimeBest = binaryEndBest - binaryStartBest

binaryStartAvg = datetime.now()
binaryIndexAvg = binary_search(data, 0, len(data) - 1, data[24000])
binaryEndAvg = datetime.now()
binaryTimeAvg = binaryEndAvg - binaryStartAvg

binaryStartWorst = datetime.now()
binaryIndexWorst = binary_search(data, 0, len(data) - 1, -1)
binaryEndWorst = datetime.now()
binaryTimeWorst = binaryEndWorst - binaryStartWorst

print(
    f'For Index of {binaryIndexBest}.Time taken by binary search {binaryTimeBest}'
)
print(
    f'For Index of {binaryIndexAvg}.Time taken by binary search {binaryTimeAvg}'
)
print(
    f'For Index of {binaryIndexWorst}.Time taken by binary search {binaryTimeWorst}'
)
示例#34
0
 def test_banary_search_with_empty_list(self):
     names = []
     assert binary_search(names, 'No one') is None
示例#35
0
import random
from search import linear_search, binary_search
from datetime import datetime

data = random.sample(range(1000000000), 1000000)
linear_start = datetime.now()
linear_index = linear_search(data, data[-1])
linear_end = datetime.now()
linear_elapsed = linear_end - linear_start
data = sorted(data)
binary_start = datetime.now()
binary_index = binary_search(data, 0, len(data) - 1, data[-1])
binary_end = datetime.now()
binary_elapsed = binary_end - binary_start

print(f'Found at {linear_index}.Time taken by linear search {linear_elapsed}')
print(f'Found at {binary_index}.Time taken by binary search {binary_elapsed}')
 def test_search(self):
     data = [1, 2, 3, 4, 5, 6, 7, 8, 12]
     self.assertEqual(binary_search(data, 9), -1)
     self.assertEqual(binary_search(data, 3), 2)
     self.assertEqual(binary_search(data, 1), 0)
     self.assertEqual(binary_search(data, 7), 6)
示例#37
0
def test_search() -> None:
    """Simple test for binary_search."""
    assert binary_search([0, 5, 10, 15, 20, 25, 30, 35, 40], 5) == -1
示例#38
0
def test_search():
    """Simple test for binary_search."""
    assert binary_search(XXXX, XXXX) == XXXX
示例#39
0
from search import binary_search

arr = ['B', 'E', 'K', 'J', 'A', 'U', 'P']
element = 'J'

def insert_sort (arr):
    # symbols sorted base on ord(ascii symbols)
    for i in range(1, len(arr)):
        j = i
        while j >0 and arr[j] <= arr[j-1]:
            arr[j], arr[j-1] = arr[j-1], arr[j]
            j-=1
    return arr

sorted_arr = insert_sort(arr)

index = binary_search(sorted_arr, element)

print(index)