def test_doesnot_contain_an_integer(self): input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] bs = BinarySearch(input) result = bs.contains(22) assert result is False
def main(): print("Test cases: ") print("1. 100 numbers") print("2. 1000 numbers") print("3. 5000 numbers") print("4. Exit") answer = int(input("Enter a test case option >> ")) bsAvg = 0 isAvg = 0 while answer != 4: if answer == 1: list = sorted(ListGenerator(101)) for i in range(5): number = random.randint(1, 32767) bsAvg += BinarySearch(number, list) isAvg += InterpolationSearch(number, list) print("Binary Search average time: ", bsAvg / 5) print("Interpolation Search average time: ", isAvg / 5) print("Test cases: ") print("1. 100 numbers") print("2. 1000 numbers") print("3. 5000 numbers") print("4. Exit") answer = int(input("Enter a test case option >> ")) elif answer == 2: list = sorted(ListGenerator(1001)) for i in range(5): number = random.randint(1, 32767) bsAvg += BinarySearch(number, list) isAvg += InterpolationSearch(number, list) print("Binary Search average time: ", bsAvg / 5) print("Interpolation Search average time: ", isAvg / 5) print("Test cases: ") print("1. 100 numbers") print("2. 1000 numbers") print("3. 5000 numbers") print("4. Exit") answer = int(input("Enter a test case option >> ")) elif answer == 3: list = sorted(ListGenerator(5001)) for i in range(5): number = random.randint(1, 32767) bsAvg += BinarySearch(number, list) isAvg += InterpolationSearch(number, list) print("Binary Search average time: ", bsAvg / 5) print("Interpolation Search average time: ", isAvg / 5) print("Test cases: ") print("1. 100 numbers") print("2. 1000 numbers") print("3. 5000 numbers") print("4. Exit") answer = int(input("Enter a test case option >> ")) print("\n\t.\n\t.\n\t.\n\n...Exiting...")
def three_sum_fast(list): n = len(list) cnt = 0 list.sort() search = BinarySearch(list) for i in range(n): for j in range(i + 1, n): if (search.search(-list[i] - list[j]) > j): cnt += 1 return cnt
def test_BinarySearch(self): A = [0, 1, 2, 3, 4, 5] #Tests for element which are on the list self.assertEqual(BinarySearch(A, 0), 0) self.assertEqual(BinarySearch(A, 1), 1) self.assertEqual(BinarySearch(A, 2), 2) #Tests for element which are not on the list self.assertEqual(BinarySearch(A, 10), -1) self.assertEqual(BinarySearch(A, 11), -1)
def main(): #Data Structures LinkedList.test() QueueArray.test() QueueLL.test() ResizingArray.test() HashTable.test() BinarySearchTree.test() Heap.test() Trie.test() GraphTraversal.test() #Search / Sort BinarySearch.test() BubbleSort.test()
def source_data(path): # AIS存储网格区域 grids = [{time_: list()} for time_ in date_range(start, end, step)] with open(path) as f_object: datas = csv.reader(f_object) # data: ['MMSI', 'TIME', 'LON', 'LAT', 'COG', 'SOG'] next(datas) for data in datas: # 根据经、纬度(data[2], data[3])确定网格编号area_ID if int(data[2][4]) >= 5 or int(data[3][3]) >= 5: _lon = int(data[2][:3]) + 0.5 _lat = int(data[3][:2]) + 0.5 else: _lon = int(data[2][:3]) _lat = int(data[3][:2]) print("_lon: ", _lon, "_lat: ", _lat) lon_remainder = int(*np.where(longitude == _lon)) lat_quotient = int(*np.where(latitude == _lat)) area_ID = lat_quotient * Lon_Length + lon_remainder time = parse_time(data[1]) time_remainder = time.second % 10 if time_remainder in range(8, 10): s = 10 - time_remainder _time = time + timedelta(seconds=s) elif time_remainder in range(0, 3): _time = time - timedelta(seconds=time_remainder) elif time_remainder in range(3, 6): s = 5 - time_remainder _time = time + timedelta(seconds=s) else: s = time_remainder - 5 _time = time - timedelta(seconds=s) grids[BinarySearch(grids, _time)][_time].append(Vessel(area_ID, data)) return grids
def count(a): a.sort() N = len(a) cnt = 0 for i in range(N): if BinarySearch.rank(-a[i], a) > i: cnt += 1 return cnt
def count(a): a.sort() N = len(a) cnt = 0 for i in range(N): for j in range(i + 1, N): if BinarySearch.rank(-a[i] - a[j], a) > j: cnt += 1 return cnt
def source_data(path, *, longitude, latitude, delta, **kwargs): lon_length = longitude.size # AIS存储网格区域 # grids = [{time_: list()} for time_ in date_range(start, end, step)] grids = [{"TIME": time_, "SHIP_INFO": list()} for time_ in date_range( kwargs['start'], kwargs['end'], kwargs['step'] ) ] with open(path) as f_object: datas = csv.reader(f_object) # data: ['MMSI', 'TIME', 'LON', 'LAT', 'COG', 'SOG'] next(datas) for data in datas: lon, lat = data[2], data[3] lon_, lat_ = 0, 0 # 根据经、纬度(data[2], data[3])确定网格编号area_ID if int(lon[4]) < 5 and int(lat[3]) < 5: lon_ = int(lon[: 3]) lat_ = int(lat[: 2]) elif int(lon[4]) >= 5 and int(lat[3]) >= 5: lon_ = int(lon[: 3]) + 0.5 lat_ = int(lat[: 2]) + 0.5 elif int(lon[4]) < 5 and int(lat[3]) >= 5: lon_ = int(lon[: 3]) lat_ = int(lat[: 2]) + 0.5 elif int(lon[4]) >= 5 and int(lat[3]) < 5: lon_ = int(lon[: 3]) + 0.5 lat_ = int(lat[: 2]) else: print("") print("Can't convert to grid index!!!") print("Can't find {}/{}".format(lon, lat)) print("_lon: ", lon_, "_lat: ", lat_) lon_remainder = int(*np.where(longitude == lon_)) lat_quotient = int(*np.where(latitude == lat_)) # are_id 根据该船当前时刻的经、纬度, 判断出该船所属网格编号 area_id = lat_quotient * lon_length + lon_remainder time = parse_time(data[1]) time_remainder = time.second % 10 if time_remainder in range(8, 10): s = 10 - time_remainder _time = time + timedelta(seconds=s) elif time_remainder in range(0, 3): _time = time - timedelta(seconds=time_remainder) elif time_remainder in range(3, 6): s = 5 - time_remainder _time = time + timedelta(seconds=s) else: s = time_remainder - 5 _time = time - timedelta(seconds=s) grids[BinarySearch(grids, _time)]["SHIP_INFO"].append(Vessel( area_id, data, gridlon_=longitude, gridlat_=latitude, grid_delta=delta )) return grids
def countFast(input): start = time() cnt = 0 result = [] input.sort() for i in range(len(input)): if BinarySearch(input, -input[i]) > i: result.append([input[i], -input[i]]) cnt += 1 end = time() print('time: %s, count: %d' % (end - start, cnt))
def setUp(self): self.one_to_twenty = BinarySearch(20, 1) self.two_to_forty = BinarySearch(20, 2) self.ten_to_thousand = BinarySearch(100, 10)
class BinarySearchTest(unittest.TestCase): """Get the index of the item with an expected number of loops in\ array [1, 2 . . . 20] Returns a dictionary containing {count: value, index: value} """ def setUp(self): self.one_to_twenty = BinarySearch(20, 1) self.two_to_forty = BinarySearch(20, 2) self.ten_to_thousand = BinarySearch(100, 10) def test_small_list_search(self): search = self.one_to_twenty.search(16) self.assertGreater( 5, search['count'], msg='should return {count: 4, index: 15} for 16' ) self.assertEqual( 15, search['index'], msg='should return {count: 4, index: 15} for 16' ) def test_medium_list_search(self): search1 = self.two_to_forty.search(16) search2 = self.two_to_forty.search(40) search3 = self.two_to_forty.search(33) self.assertGreater( 5, search1['count'], msg='should return {count: 4, index: 7} for 16' ) self.assertEqual( 7, search1['index'], msg='should return {count: 4, index: 7} for 16' ) self.assertEqual( 0, search2['count'], msg='should return {count: 0, index: 19} for 40' ) self.assertEqual( 19, search2['index'], msg='should return {count: 5, index: 19} for 40' ) self.assertGreater( 4, search3['count'], msg='should return {count: 3, index: -1} for 33' ) self.assertEqual( -1, search3['index'], msg='should return {count: 3, index: -1} for 33' ) def test_large_list_search(self): search1 = self.ten_to_thousand.search(40) search2 = self.ten_to_thousand.search(880) search3 = self.ten_to_thousand.search(10000) self.assertGreater( 7, search1['count'], msg='should return {count: # <= 7, index: 3} for 40' ) self.assertEqual( 3, search1['index'], msg='should return {count: # <= 7, index: 3} for 40' ) self.assertGreater( 4, search2['count'], msg='should return {count: # <= 3, index: 87} for 880' ) self.assertEqual( 87, search2['index'], msg='should return {count: # <= 3, index: 87} for 880' ) self.assertGreater( 7, search3['count'], msg='should return {count: 3, index: -1} for 10000' ) self.assertEqual( -1, search3['index'], msg='should return {count: 3, index: -1} for 10000' )
def testBinarySearchChecker(self): """Fail to Find Designated Number - your Algorithm is wrong""" array = [7, 10, 20, 21, 23, 29, 30, 56, 32] self.assertEqual(BinarySearch(array, random.choice(array)), True)
def test_isPresent_begin_index_is_negative_should_throw_exception(self): array = [1, 2, 3, 4, 5, 6, 7] search = BinarySearch(array) self.assertEqual(search.is_present(-1, 5), None)
def test_isPresent_end_index_is_greater_than_array_length_should_throw_exception( self): array = [1, 2, 3, 4, 5, 6, 7] search = BinarySearch(array) self.assertEqual(search.is_present(0, 10), None)
def __init__(self): self.Binary_Search = BinarySearch() # 实例一个二分法过滤器 self.Queue = Queue(100000) # 实例一个队列 self.thread_count = 10 # 线程数 self.lock = Lock() # 线程锁 self.event = Event()
#!/usr/bin/python from BinarySearch import BinarySearch bs = BinarySearch() print bs.binSearch([1, 4, 5, 12, 14, 19, 22], 4)
def __init__(self, playerId): self.id = playerId self.shots = BinarySearch()
if __name__ == '__main__': linked_list = LinkedList() linked_list.append_node(55) linked_list.append_node(60) linked_list.append_node(65) linked_list.append_node_to_beginning(20) linked_list.append_data_after(linked_list.head.next, 30) print('The created linked list is: ') linked_list.print_nodes() Months().pi_day() BirthdayPlaces().display_places() SweepStakes().pick_winner() trunk = Node(50) trunk = trunk.insert(trunk, 30) trunk = trunk.insert(trunk, 20) trunk = trunk.insert(trunk, 40) trunk = trunk.insert(trunk, 70) trunk = trunk.insert(trunk, 60) trunk = trunk.insert(trunk, 80) trunk.inorder(trunk) trunk.pre_order(trunk) print('The Binary Search: ') r = BinarySearch(50) r = r.insert(r, 30) r = r.insert(r, 20) r = r.insert(r, 40) r = r.insert(r, 70) r = r.insert(r, 60) r = r.insert(r, 80)
#Time calculations linear search for i in range(n, n * 10, n): sizeArray.append(i) randomvalues = random.sample(range(i), i) startTime = time() LinearSearch(randomvalues, randomvalues[i - 1]) endTime = time() totalTime = endTime - startTime timeLinear.append(totalTime) print(totalTime, "for size", i) n = 100000 i = 0 #Time Plotting for the binary search for i in range(n, n * 10, n): randomvalues = random.sample(range(i), i) startTime = time() BinarySearch(randomvalues, randomvalues[i - 1]) endTime = time() totalTime = endTime - startTime timeBinary.append(totalTime) print(totalTime, "for size", i) # draw graph for time vs size for both algorithms fig, ax = plt.subplots(1, 1) ax.plot(sizeArray, timeLinear, label='Linear Search') ax.plot(sizeArray, timeBinary, label='Binary Search') legend = ax.legend(loc='upper center', shadow=True, fontsize='large') plt.show()
def test_creates_instance(self): input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] bin = BinarySearch(input) assert bin is not None
class spider(): def __init__(self): self.Binary_Search = BinarySearch() # 实例一个二分法过滤器 self.Queue = Queue(100000) # 实例一个队列 self.thread_count = 10 # 线程数 self.lock = Lock() # 线程锁 self.event = Event() def requstGET(self, url): ''' 请求函数 :param url: url :return: text ''' try: response = requests.get(url, headers=headers, timeout=3, verify=False) response.encoding = response.apparent_encoding if response.status_code == 200: return response.text except Exception as e: return None def parser(self, url): ''' 解析网页,取得url保存至队列 :param url: :return: ''' url_hash = self.Binary_Search.hash(url) self.lock.acquire() # 线程锁 if self.Binary_Search.exists(self.Binary_Search.container, url_hash): # 判断url是否在布隆过滤器中 self.lock.release() # 解锁 return None # 在过滤器中直接结束函数 self.Binary_Search.container.append(url_hash) # 不在过滤器中,添加到过滤器中 self.Binary_Search.container.sort() self.lock.release() # 解锁 print(url) text = self.requstGET(url) # 请求url if text: soup = BeautifulSoup(text, 'html.parser') # 解析url for link in soup.find_all('a'): self.Queue.put_nowait(link.get('href')) # 取得新url保存到队列 self.event.wait() def thread_pool(self): ''' 线程池,从队列中取出url,循环开启子线程 :return: ''' while True: task_list = [] for i in range(0, self.thread_count): # 每次开启 thread_count 个线程 try: task_list.append( Thread(target=self.parser, args=(self.Queue.get_nowait(), ))) #创建子线程任务 except Exception as e: print(e) for task in task_list: # 开启线程任务 time.sleep(0.5) task.start() # [task.join() for task in task_list] # 等待这批线程全部结束 time.sleep(5) self.event.set() print(self.Queue.qsize())
def test_contains_an_integer(self): input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] bs = BinarySearch(input) result = bs.contains(5) assert result is True
from HelloWorld import PrintHelloWorld, Add from BinarySearch import BinarySearch result = BinarySearch([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5) print(result) Add(2, 3) PrintHelloWorld()