def call_linear_search(value_sought):
    """Call the iterative version of the binary search"""
# We need to do make a subroutine call in the scope of time_searches so we can
# pass the global variable corpus.  corpus is out of scope of the actual
# binary search routine, so we have to pass it (it gets passed by reference,
# which is fast)
    linear_search.linear_search(corpus, value_sought)   
Пример #2
0
 def test_linear_search_raises_an_error_with_an_invalid_target(self):
     target = 1
     try:
         linear_search(self.unsorted_values, target)
     except ValueError as e:
         self.assertEqual(e.message,
                          "{} was not found in the list".format(target))
    def test_linear_search(self):
        arr1 = [-2, 7, 3, -9, 5, 1, 0, 4, -6]
        arr2 = []

        self.assertEqual(linear_search(arr1, 6), -1)
        self.assertEqual(linear_search(arr1, -6), 8)
        self.assertEqual(linear_search(arr1, 0), 6)
        self.assertEqual(linear_search(arr2, 3), -1)
Пример #4
0
	def min2d_yielded(self):
		x = self.initial_coordinates
		while self.norm(self.g(x)) > self.eps:
			ls = linear_search(x, self.f, self.g(x), self.eps)
			p_0 = ls.min()

			ls = linear_search(p_0, self.f, self.g(p_0), self.eps)
			p_1 = ls.min()

			d = map(op.sub, p_1, x)

			ls = linear_search(x, self.f, d, self.eps)
			x = ls.min()
			yield p_0, p_1, x
Пример #5
0
def dotest(terms, expected, which):
    files = filelist(rootdir)
    terms = words(terms)
    # print(terms)

    if which == 0:
        linear_docs = linear_search(files, terms)
        # print(filenames(linear_docs))
        names = filenames(linear_docs)
        names.sort()
        expected.sort()	
        #assert filenames(linear_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
    elif which == 1:
        index = create_index(files)
        index_docs = index_search(files, index, terms)
        # print(filenames(index_docs))
        names = filenames(index_docs)
        names.sort()
        expected.sort()
        #assert filenames(index_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
    else:
        index = myhtable_create_index(files)
        index_docs = myhtable_index_search(files, index, terms)
        # print(filenames(index_docs))
        names = filenames(index_docs)
        names.sort()
        expected.sort()
        #assert filenames(index_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
Пример #6
0
def dotest(terms, expected, which):
    files = filelist(rootdir)
    terms = words(terms)
    # print(terms)

    if which == 0:
        linear_docs = linear_search(files, terms)
        # print(filenames(linear_docs))
        names = filenames(linear_docs)
        names.sort()
        expected.sort()	
        #assert filenames(linear_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
    elif which == 1:
        index = create_index(files)
        index_docs = index_search(files, index, terms)
        # print(filenames(index_docs))
        names = filenames(index_docs)
        names.sort()
        expected.sort()
        #assert filenames(index_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
    else:
        index = myhtable_create_index(files)
        index_docs = myhtable_index_search(files, index, terms)
        # print(filenames(index_docs))
        names = filenames(index_docs)
        names.sort()
        expected.sort()
        #assert filenames(index_docs) == expected
        assert names == expected, "found "+str(names)+" != expected "+str(expected)
Пример #7
0
def time_check(choice: str, ite: int):
    l = []
    lim = 10000000
    if choice == 'sorted':
        for i in range(lim):
            l.append(random.randint(0, lim))
        l.sort()

    elif choice == 'normalized':
        for i in range(lim):
            l.append(i)

    inter = []
    seq = []
    bnry = []
    indexed = []

    for i in range(0, ite):
        value = random.randint(0, lim)
        if (choice == 'normalized'):
            start2 = time.clock()
            ret1 = interpolation_search(l, value)
            end2 = time.clock()
            if ret1 == True:
                time2 = end2 - start2
                inter.append(time2)

        start1 = time.clock()
        ret2 = linear_search(l, value)
        end1 = time.clock()
        if ret2 == True:
            time1 = end1 - start1
            seq.append(time1)

        start3 = time.clock()
        ret3 = binary_search(l, value)
        end3 = time.clock()
        if ret3 == True:
            time3 = end3 - start3
            bnry.append(time3)

        start4 = time.clock()
        ret4 = index_search(l, value)
        end4 = time.clock()
        if ret4 == True:
            time4 = end4 - start4
            indexed.append(time4)

    plt.xlabel('Iterations')
    plt.ylabel('Time')
    if len(inter) != 0:
        plt.plot(inter, color='red', label='interpolation')
    plt.plot(seq, color='green', label='sequential')
    plt.plot(bnry, color='blue', label='binary')
    plt.plot(indexed, color='purple', label='indexed')
    plt.legend()
    plt.grid(True)
    plt.show()
Пример #8
0
def main():
    '''Main Function able to run all algorithms present in List_Algorithms.txt '''
    file = open('List_Algorithms.txt', "r")
    lines = list(file)
    for line in lines:
        print(line.strip('\n'))
    file.close()
    algorithm_to_call = int(
        input("Enter the number from below list algorithms :\n"))
    #PRIME CHECK CALL
    if algorithm_to_call == 1:
        print("You Have Selected PrimeCheck")
        from prime_check_file import prime_check
        if prime_check(int(
                input("Enter a number to check Prime/Not Prime :"))):
            print("It is a Prime Number")
        else:
            print("Not a Prime Number!")
#Binary_Search_recursive algorithm_to_call
    if algorithm_to_call == 2:
        from binary_search_recursive import binary_search_rec
        print("You Have Selected Binary_Search_recursive algorithm")
        elements = [
            int(i) for i in input(
                "Enter List of number in Ascending Order\n").split()
        ]
        item = int(input("Enter Item you want to Search :\n"))
        print("[Recursive Binary search function called]")
        print(binary_search_rec(item, elements, 0, len(elements), 0))
#Binary_Search_iterative algorithm_to_call
    if algorithm_to_call == 3:
        from binary_search_iterative import binary_search_iter
        print("You Have Selected Binary_Search_iterative algorithm")
        elements = [
            int(i) for i in input(
                "Enter List of number in Ascending Order\n").split()
        ]
        item = int(input("Enter Item you want to Search :\n"))
        print(binary_search_iter(item, elements, 0, len(elements), 0))
#Linear Search algorithm_to_call
    if algorithm_to_call == 4:
        from linear_search import linear_search
        print("You Have Selected linear search algorithm")
        elements = [int(i) for i in input("Enter List of numbers\n").split()]
        item = int(input("Enter number you want to search :\n"))
        print(linear_search(elements, item))


#Jump Search algorithm_to_call
    if algorithm_to_call == 5:
        import math
        from jump_search import jump_search
        print("You Have Selected jump search algorithm")
        elements = [int(i) for i in input("Enter List of numbers\n").split()]
        item = int(input("Enter number you want to search :\n"))
        print(jump_search(elements, item, 0, int(math.sqrt(len(elements))), 0))
Пример #9
0
	def min(self, error = None):
		if error == None:
			error = lambda _x: self.norm(self.g(_x))

		x = self.initial_coordinates

		while error(x) > self.eps:
			ls = linear_search(x, self.f, self.g(x), self.eps)
			p_0, eta_4 = ls.min()

			ls = linear_search(p_0, self.f, self.g(p_0), self.eps)
			p_1, eta_4 = ls.min()

			d = map(op.sub, p_1, x)

			ls = linear_search(x, self.f, d, self.eps)
			x, eta_4 = ls.min()
			print 'x =', x
		return x
Пример #10
0
def tester():

    item = 20
    list_one = [10,20,40,50,56,2,4,5,7,8,10,120,67,45,
    24,27,62,65,78,28,77,69,65,58,66,88,100,73,88,16,
    39,58,68,49,59,72,50,76,6782,36,100,22,17,81,70,42,
    88,85,23,25,42,41,83,43,60,75,46,79,12,18,6,43,
    17,42,56,89,50,94,72,68,43,82,53,82,11,94,63,74,67,
    65,77,96,95,61,85,9,26,91,91,44,83,7,90,71,37,73,85,14]

    print "Number {} is found at position : {}".format(item,linear_search(list_one,item))
Пример #11
0
def test_linear_berlitz_none():
    terms = "missspellinnng"

    files = filelist(rootdir)

    terms = words(terms)

    linear_docs = linear_search(files, terms)

    expected = []
    assert filenames(linear_docs)==expected
Пример #12
0
def test_linear_berlitz():
    terms = "hawaii travel"

    files = filelist(rootdir)

    terms = words(terms)

    linear_docs = linear_search(files, terms)

    expected = ['HistoryHawaii.txt']
    assert filenames(linear_docs)==expected
Пример #13
0
def test_linear_berlitz():
    terms = "hawaii travel"

    files = filelist(rootdir)

    terms = words(terms)

    linear_docs = linear_search(files, terms)

    expected = ['HistoryHawaii.txt']
    assert filenames(linear_docs) == expected
Пример #14
0
def test_linear_berlitz_none():
    terms = "missspellinnng"

    files = filelist(rootdir)

    terms = words(terms)

    linear_docs = linear_search(files, terms)

    expected = []
    assert filenames(linear_docs) == expected
Пример #15
0
def time_search_algorithms(list_length=1, generator=random_list):
    # generate a sample list and search_item
    search_list = generator(list_length=list_length)
    search_item = random.randint(0, 10000)

    # dictionary for storing values
    times = {}
    # keep track of list length
    times['length'] = list_length

    start_time = timeit.default_timer()
    linear_search(search_list, search_item)
    duration = timeit.default_timer() - start_time
    times['linear'] = duration

    start_time = timeit.default_timer()
    binary_search(sorted(search_list), search_item)
    duration = timeit.default_timer() - start_time
    times['binary'] = duration

    return times
Пример #16
0
def test_linear_search():
    assert linear_search([1, 2, 3, 4, 5], 2) == 1
    assert linear_search([1, 2, 3, 4, 5], -4) == -1
    assert linear_search([], 0) == -1
    assert linear_search([9, 9, 9], 9) == 0
    assert linear_search([-9, 2, 5, -1, 11432, 2, 6], 11432) == 4
    assert linear_search([-9, 2, 5, -1, 11432, 2, 6], 6) == 6
Пример #17
0
    def plotComplexityLinear(self):
        random_values = random.sample(range(1000000), 1000000)
        sortedX = sorted(random_values)
        time_taken = {}
        step_size = 10000

        for _ in range(int(len(sortedX) / step_size)):
            start_time = time()

            x = linear_search(sortedX, sortedX[-1])
            #x=binary_search(sortedX,sortedX[-1])

            end_time = time()
            time_taken[len(sortedX)] = end_time - start_time
            sortedX = sortedX[step_size:]
        return time_taken
Пример #18
0
  def fit(self, start_points):
    start_points = np.array(start_points)
    assert len(start_points) == len(self.X_)

    result = [start_points]
    points = copy.deepcopy(start_points)
    points = np.array(points, np.double)

    kv = lambda x : {var : val for var, val in zip(self.X_, x)}
    dx = lambda x : np.array([dfx.subs(kv(x)) for dfx in self.DFX_], np.double)

    for i in range(1000):
      d = dx(points)
      if np.linalg.norm(d) < self.threshold_:
        break
      d = self.norm(d)
      alpha = linear_search(points, self.X_, self.FX_, d, self.threshold_ / 10)
      points = points + alpha * d
      result.append(points)
    return result
Пример #19
0
    def fit(self, start_values):
        start_values = np.array(start_values)
        assert len(start_values) == len(self.X_)

        result = [start_values]
        x = copy.deepcopy(start_values)
        x = np.array(x, np.double)

        d = 0
        alpha = 0
        for i in range(1000):
            d = -self.dx(x) + alpha * d
            if np.linalg.norm(d) < self.threshold_:
                break
            l = linear_search(x, self.X_, self.FX_, d, self.threshold_ / 10)
            x0 = np.copy(x)
            x = x + l * d
            result.append(x)
            alpha = self.alpha_func_(self.dx, x0, x)
        return result
Пример #20
0
    def test_linear_search_returns_an_index(self):
        position = linear_search(self.unsorted_values, self.target)

        assert position in range(self.items_length)
        assert isinstance(position, int)
Пример #21
0
 def test_linear_search_finds_target(self):
     position = linear_search(self.unsorted_values, self.target)
     self.assertEqual(self.unsorted_values[position], self.target)
import linear_search  # type: ignore
import binary_search  # type: ignore
import random

if __name__ == '__main__':
    list_size = int(input('List size: '))
    list = sorted([random.randint(0, 100) for i in range(list_size)])
    # print(list)

    goal = int(input('Which number do you want to find?: '))

    print('-----')
    print('LINEAR SEARCH:')
    (found, iter_lin) = linear_search.linear_search(list, goal)
    print(f'It took {iter_lin} iterations')
    print(f'The goal element {goal} {"is" if found else "is not"} in the list')

    print('-----')
    print('BINARY SEARCH:')
    (found, iter_bin) = binary_search.binary_search(list, 0,
                                                    len(list) - 1, goal)
    print(f'It took {iter_bin} iterations')
    print(f'The goal element {goal} {"is" if found else "is not"} in the list')
Пример #23
0
def test_valid_neg_input():
    result = linear_search(1000, 5120)
    assert result == False
Пример #24
0
 def test_linear_search_finds_target(self):
     position = linear_search(self.unsorted_values, self.target)
     self.assertEqual(self.unsorted_values[position], self.target)
import ternary_search as ts
import binary_search as bs
import linear_search as ls

l1 = [16, 20, 26, 30, 36, 40, 46, 50, 56, 60, 66, 70, 76, 80]
target = 76

ternary_search = ts.ternary_search(l1, target)
ternary_search.ternary_search()

binary_search = bs.binary_search(l1, target)
binary_search.binary_search()

linear_search = ls.linear_search(l1, target)
linear_search.linear_search()
 def test_general_case(self):
     arr = [1, 6, 3, 8, 9, 5]
     val = 8
     self.assertEqual(linear_search(arr, val), 3)
Пример #27
0
    def test_linear_search_returns_an_index(self):
        position = linear_search(self.unsorted_values, self.target)

        assert position in range(self.items_length)
        assert isinstance(position, int)
Пример #28
0
def test_linear_search_did_not_find_target():
	iterable = ["apple", "grape", "orange"]
	assert linear_search(iterable, "banana") == False
Пример #29
0
def test_linear_search_find_target():
	iterable = ["apple", "grape", "orange"]
	assert linear_search(iterable, "grape") == True
Пример #30
0
 def test_not_in_the_list(self):
     items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
     x = 0
     self.assertEqual(None, linear_search(items, x))
Пример #31
0
 def test_first_item(self):
     items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
     x = 1
     self.assertEqual(0, linear_search(items, x))
Пример #32
0
 def test_simple(self):
     items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
     x = 5
     self.assertEqual(4, linear_search(items, x))
Пример #33
0
 def test_unsorted(self):
     items = [1, 5, 9, 4, 2, 6, 7, 8, 3]
     x = 6
     self.assertEqual(5, linear_search(items, x))
Пример #34
0
from time import time
import random
from linear_search import linear_search

random_values = random.sample(range(1000000), 1000000)
sortedX = sorted(random_values)
start_time = time()
linear_search(random_values, 999999)
end_time = time()
time_taken = end_time - start_time
print("Time taken for the operation is ", time_taken)
from linear_search import linear_search

print(linear_search(3, [1, 2, 3]) == 2)
print(linear_search(4, [1, 2, 3]) == None)
print(linear_search(13, [1, 2, 3]) == None)
Пример #36
0
import random
import matplotlib.pyplot as plt
from linear_search import linear_search
from timeit import default_timer as timer

data_size = list()
best_case = list()
worst_case = list()

for i in range(1000, 100001, 500):
    data = random.sample(range(100000), i)
    data_size.append(i)

    start_time_worst = timer()
    linear_search(data, data[-1])
    worst_case.append(timer() - start_time_worst)

    start_time_best = timer()
    linear_search(data, data[0])
    best_case.append(timer() - start_time_best)

plt.plot(data_size, best_case, 'g', label="Best Case")
plt.plot(data_size, worst_case, 'r', label="Worst Case")
plt.xlabel("Data Size")
plt.ylabel("Time Taken")
plt.title("Best and Worst case Time Complexity of Linear Search")
plt.legend()
plt.savefig('Linear Search.png', dpi=300, format='png', pad_inches=1.0)
plt.show()
Пример #37
0
 def test_linear_search_raises_an_error_with_an_invalid_target(self):
     target = 1
     try:
         linear_search(self.unsorted_values, target)
     except ValueError as e:
         self.assertEqual(e.message, "{} was not found in the list".format(target))
Пример #38
0
impl = sys.argv[1]
rootdir = sys.argv[2]
files = filelist(rootdir)
# Uncomment the next line to test just the first 100 files instead of all files
# files = files[:100]
N = len(files)
print(N, "files")

index = None

while True:
    terms = input("Search terms: ")
    terms = words(terms)

    if impl=='linear':
        docs = linear_search(files, terms)
    elif impl == 'index':
        if index is None:
            index = create_index(files)
            print("Index complete")
        docs = index_search(files, index, terms)
    elif impl == 'myhtable':
        if index is None:
            index = myhtable_create_index(files)
            print("Index complete")
        docs = myhtable_index_search(files, index, terms)
    else:
        print("Invalid search type:", impl)
        break
    page = results(docs, terms)
    with open("/tmp/results.html", "w", encoding='UTF-8') as f:
 def test_element_not_in_list(self):
     arr = [1, 6, 3, 8, 9, 5]
     val = 2
     self.assertIsNone(linear_search(arr, val))
 def test_empty_list(self):
     arr = []
     val = 42
     self.assertIsNone(linear_search(arr, val))
 def test_singleton_list(self):
     arr = [5]
     val = 5
     self.assertEqual(linear_search(arr, val), 0)
Пример #42
0
 def test_search_first(self):
     self.assertEqual(0, search.linear_search(self.my_list, 3))
Пример #43
0
def test_valid_pos_input():
    result = linear_search(1000, 50)

    assert result == True
Пример #44
0
 def test_search_last(self):
     self.assertEqual(6, search.linear_search(self.my_list, 78))
Пример #45
0
def test_invalid_input():
    result = linear_search(0, 0)
Пример #46
0
 def test_search_inexisting(self):
     self.assertEqual(-1, search.linear_search(self.my_list, 4))
 def test_last_element_is_value(self):
     arr = [1, 6, 3, 8, 9, 5]
     val = 5
     self.assertEqual(linear_search(arr, val), 5)
Пример #48
0
 def test_search_item(self):
     self.assertEqual(2, search.linear_search(self.my_list, 12))
Пример #49
0
 def TestPassed(self):
     self.assertAlmostEqual(ls.linear_search(-(math.pi / 2), math.pi / 2),
                            -1.57079600431)
     print("OK.")
Пример #50
0
 def test_last_item(self):
     items = [1, 2, 3, 4, 5, 6, 7, 8, 9]
     x = 9
     self.assertEqual(8, linear_search(items, x))
Пример #51
0
impl = sys.argv[1]
rootdir = sys.argv[2]
files = filelist(rootdir)
# Uncomment the next line to test just the first 100 files instead of all files
# files = files[:100]
N = len(files)
print N, "files"

index = None

while True:
    terms = raw_input("Search terms: ")
    terms = words(terms)

    if impl == 'linear':
        docs = linear_search(files, terms)
    elif impl == 'index':
        if index is None:
            index = create_index(files)
            print "Index complete"
        docs = index_search(files, index, terms)
    elif impl == 'myhtable':
        if index is None:
            index = myhtable_create_index(files)
            print "Index complete"
        docs = myhtable_index_search(files, index, terms)
    else:
        print "Invalid search type:", impl
        break
    page = results(docs, terms)
    f = open("/tmp/results.html", "w")
 def test_search(self):
     data = [1, 2, 3, 5, 6, 12, 7, 4, 8]
     self.assertEqual(linear_search(data, 6), 4)
     self.assertEqual(linear_search(data, 10), -1)