def sink(): """Sink thread function""" # Create new ZeroMQ context. context = zmq.Context() # Configure ZeroMQ sink socket. sink_socket = context.socket(zmq.PULL) sink_socket.bind("tcp://*:18888") # Configure ZeroMQ publishing socket. kill_socket = context.socket(zmq.PUB) kill_socket.bind("tcp://*:19999") start = time.time() # Thread loop. results = [] for _ in range(constants.NUMBER_OF_WORKERS): results = results + sink_socket.recv_pyobj() print "Result received.." merge_sort(results) end = time.time() print end - start # Kill worker threads. kill_socket.send(b"kill")
def test_none(self): array = None # one way to test for exceptions using a context manager with self.assertRaises(TypeError): merge_sort(array) # another way to test for exceptions using a function self.assertRaises(TypeError, merge_sort, array)
def test_merge_sort_random(self): for i in range(4): a = [] for _ in range(i): a.append(random.randint(1, 10000)) s = sorted(a) sort.merge_sort(a) self.assertEqual(a, s)
def sort_dict(edges): indexes = [] result = {} for k, v in edges.items(): indexes.append(k) #Сортировка слиянием (код в файле sort.py) sort.merge_sort(indexes) for i in indexes: for k, v in edges.items(): if i == k: result[i] = v return result
def test_sort(self): # Set up array to sort array_len = 1024 max_value = 1024 x = [random.randint(0, max_value) for i in range(array_len)] # Insertion sort self.assertEqual(sort.insertion_sort(x), sorted(x)) # Merge sort self.assertEqual(sort.merge_sort(x), sorted(x)) # Selection sort self.assertEqual(sort.selection_sort(x), sorted(x)) # Bubble sort self.assertEqual(sort.bubble_sort(x), sorted(x)) # Heap sort self.assertEqual(sort.heap_sort(x), sorted(x)) # Quick sort self.assertEqual(sort.quick_sort(x), sorted(x)) # Quick sort v2 self.assertEqual(sort.quick_sort_v2(x), sorted(x))
def _test(*, num_lines: int, max_length: int): in_file = NamedTemporaryFile(mode='r+b') out_file = NamedTemporaryFile(mode='w+b') write_lines_to_file(in_file, num_lines, max_length) merge_sort(in_file, out_file, chunk_size=1_000) out_file.seek(0) src = out_file.readlines() in_file.seek(0) dst = sorted(in_file.readlines()) try: assert src == dst finally: in_file.close() out_file.close()
def count_inversions(numbers): if len(numbers) <= 1: return (0, numbers) pivot = len(numbers) // 2 (left_count, left) = count_inversions(numbers[0:pivot]) (right_count, right) = count_inversions(numbers[pivot:]) count = left_count + count_split_inversions(left, right) + right_count return (count, merge_sort(left + right))
def test_merge_sort_up_bottom(): print "\nmerge sort up bottom begin" count = random.randint(100, 1000) for _ in range(count): length = random.randint(5, 30) source = tool.random_list(0, 100, length) target = sort.merge_sort(source) if tool.list_is_ascend(target) is False: print source print target print "" assert (tool.list_is_ascend(target)) print "merge sort up bottom success in {0} times.\n".format(count)
def suffix_array(text): l = len(text) sa = list(range(l)) rank = [ord(x) for x in text] merge_sort(sa, key=lambda x: rank[x]) k = 1 while k < l: print(k) added_rank = [0] * l for i in sa: if i + k < l: added_rank[i] = rank[i + k] merge_sort(sa, key=lambda x: (rank[x], added_rank[x])) temp = [0] * l for i in range(1, l): if rank[sa[i]] == rank[sa[i - 1]] and added_rank[ sa[i]] == added_rank[sa[i - 1]]: temp[sa[i]] = temp[sa[i - 1]] else: temp[sa[i]] = temp[sa[i - 1]] + 1 temp, rank = rank, temp k *= 2 return sa
def worker(ventilator, sink, kill): """Worker thread function""" # Create new ZeroMQ context. context = zmq.Context() # Configure socket receiving work from ventilator. in_socket = context.socket(zmq.PULL) in_socket.connect(ventilator) # Configure socket sending results to sink. out_socket = context.socket(zmq.PUSH) out_socket.connect(sink) # Configure socket receiving kill signal. kill_socket = context.socket(zmq.SUB) kill_socket.connect(kill) kill_socket.setsockopt_string(zmq.SUBSCRIBE, "".decode('ascii')) # Initialize poll set. poller = zmq.Poller() poller.register(in_socket, zmq.POLLIN) poller.register(kill_socket, zmq.POLLIN) # Worker thread loop. print_and_flush(str(threading.current_thread()) + " Worker thread started..") should_continue = True while should_continue: socks = dict(poller.poll()) if in_socket in socks and socks[in_socket] == zmq.POLLIN: job = in_socket.recv_pyobj() print_and_flush(str(threading.current_thread()) + " Job received..") job = merge_sort(job) print_and_flush(str(threading.current_thread()) + " Job done..") out_socket.send_pyobj(job) if kill_socket in socks and socks[kill_socket] == zmq.POLLIN: print_and_flush(str(threading.current_thread()) + " Kill signal received..") should_continue = False # Clean up. in_socket.close() out_socket.close() kill_socket.close() context.term()
def main(): list_of_hotels = read_from_file.read_from_file("data.txt") visitors = [] rooms = [] for i in list_of_hotels: rooms.append(i.amount_of_rooms) visitors.append(i.amount_of_visitors) print(visitors) print(rooms) print("Selection sort by visitors:") start_sel = time.time() print(sort.sel_sort(visitors)) print("%f s" % (time.time() - start_sel)) print("Merge sort by rooms:") start_sel1 = time.time() print(sort.merge_sort(rooms)) print(time.time() - start_sel1) print(sort.counter)
def tests_merge_sort(self): """ Test Merge Sort. read sort.py for instructions. """ sample = [3, 1, 10, 5, 654, 45, 8, 5, 31, 123] sorted_sample = [1, 3, 5, 5, 8, 10, 31, 45, 123, 654] self.assertEqual(sorted_sample, sort.merge_sort(sample))
def main(): global RANGE global iSIZE global ROUND global PRINT size = iSIZE #Selection Sort Test test_name = "Selection Sort - unsorted" print("*******************************") print(f"Test Name:\t{test_name}") print("*******************************") sel_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() sel_sorted_lists.append(sort.selection_sort(list)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, ROUND))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Selection Sort - sorted" for i in range(0, RANGE): t1 = time.clock() sort.selection_sort(sel_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(sel_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(sel_sorted_lists[i]), round(ticks, ROUND))]) print("\n...Performing tests with reverse sorted lists...\n") test_name = "Selection Sort - reverse sorted" for i in range(0, RANGE): sel_sorted_lists[i].reverse() t1 = time.clock() sort.selection_sort(sel_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(sel_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(sel_sorted_lists[i]), round(ticks, ROUND))]) #Merge Sort Test test_name = "Merge Sort - unsorted" print("\n*******************************") print(f"Test Name:\t{test_name}") print("*******************************") merg_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() merg_sorted_lists.append(sort.merge_sort(list)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, 4))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Merge Sort - sorted" for i in range(0, RANGE): t1 = time.clock() sort.merge_sort(merg_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(merg_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(merg_sorted_lists[i]), round(ticks, 4))]) print("\n...Performing tests with sorted reverse lists...\n") test_name = "Merge Sort - reverse sorted" for i in range(0, RANGE): merg_sorted_lists[i].reverse() t1 = time.clock() sort.merge_sort(merg_sorted_lists[i]) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(merg_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(merg_sorted_lists[i]), round(ticks, 4))]) #Counting Sort Test size = iSIZE test_name = "Counting Sort - unsorted" print("\n*******************************") print(f"Test Name:\t{test_name}") print("*******************************") count_sorted_lists = [] for i in range(0, RANGE): list = myUtils.make_list(size) t1 = time.clock() count_sorted_lists.append(sort.count_sort(list, size)) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, size, ticks, ROUND) myUtils.write_to_file([(test_name, size, round(ticks, ROUND))]) size += 10 print("\n...Performing tests with sorted lists...\n") test_name = "Counting Sort - sorted" for i in range(0, RANGE): max = len(count_sorted_lists[i]) t1 = time.clock() sort.count_sort(count_sorted_lists[i], max) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, len(count_sorted_lists[i]), ticks, ROUND) myUtils.write_to_file([(test_name, len(count_sorted_lists[i]), round(ticks, ROUND))]) print("\n...Performing tests with reverse sorted lists...\n") test_name = "Counting Sort - reverse sorted" for i in range(0, RANGE): count_sorted_lists[i].reverse() max = len(count_sorted_lists[i]) t1 = time.clock() sort.count_sort(count_sorted_lists[i], max) t = time.clock() ticks = t - t1 if (PRINT): myUtils.print_pretty(i, max, ticks, ROUND) myUtils.write_to_file([(test_name, max, round(ticks, ROUND))])
sys.path.append('./') import numpy as np from search import linear_search, sentinel_linear_search, binary_search from sort import bubble_sort, quick_sort, randomized_quick_sort, insertion_sort, merge_sort A = np.random.randint(20, size=1000) seq_A = np.arange(0,10,1) #sorted_A = bubble_sort(A, 10) #print(sorted_A) #sentinel_linear_search(A, 20, 10) #linear_search(A, 20, 100) #binary_search(seq_A, 10, 2) print(A) #print("Sorted by quick-sort") #sorted_A = quick_sort(A, 1, 10) #print("Sorted by Insertion-sort") #sorted_A = insertion_sort(A,10) #print(sorted_A) #print("--------------------------------------") #print("Sorted by randomized-quick-sort") #random_sorted_A = randomized_quick_sort(A, 1, 10) #print(random_sorted_A) count = 1 sorted_A = merge_sort(A, count) print("Sorted by merged-sort") print(sorted_A)
import sort a = [71, 49, 69, 46, 43, 3, 73, 38, 77, 16, 65, 79, 80, 24, 2, 31, 55, 1, 82, 64] b = a[:] sort.merge_sort(b) print b b = a[:] sort.comb_sort(b) print b b = a[:] sort.shell_sort(b) print b b = a[:] sort.shell_sort(b, None, 'shell') print b b = a[:] sort.shell_sort(b, None, 'cuira') print b b = a[:] sort.insertion_sort(b) print b b = a[:] sort.coctail_sort(b) print b
def test_negative_values(): lst = [8, 4, 23, -42, 16, -15] expected = [-42, -15, 4, 8, 16, 23] actual = merge_sort(lst) assert actual == expected
#再帰条件の変更 import sys sys.setrecursionlimit(100000) l = list(range(3000)) random.shuffle(l) start_time = time.time() sorted_list = sort.bubble_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.selection_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.insertion_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.heap_sort(l) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.merge_sort(l) #print(sorted_list) print('time:{0:.3f}'.format(time.time()-start_time)) start_time = time.time() sorted_list = sort.quick_sort(l) print('time:{0:.3f}'.format(time.time()-start_time))
def test_large_sample(self): global large_l print('Merge sort') sort.merge_sort(large_l)
def test_sort(self): array = [6, 2, 5, 8, 1, 3, 7, 9, 4, 0] self.assertEqual(merge_sort(array), list(range(10)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #import pdb; pdb.set_trace() import random import sort def init_data(points): data = [i for i in range(points)] # shuffle data random.seed() for i in range(len(data)-1,1,-1): j = random.randint(0, i) temp = data[j] data[j] = data[i] data[i] = temp return data if __name__ == "__main__": # test_data = (19, 31, -2, 5, 42, 1, 22) test_data = init_data(100) data = list(test_data) print("Merge sort: ") print(data) sort.merge_sort(data, 0, len(data)-1) print(data)
def test_empty(self): self.assertListEqual(sort.merge_sort(list([]), order='increase'), [])
def main(): win = gp.GraphWin('sortpy', WINDOW_X, WINDOW_Y, autoflush=False) win.setBackground(color=gp.color_rgb(43, 137, 164)) print_logo() first_input = True while 1: clear_screen(win) ds = sort.generate_dataset(sort.DATA_NUM, repeat=False) bars = [] draw_bars(ds, win, bars) sort.playback_list = [] valid_command = False if first_input: command = input('Type help to view commands\n') first_input = False else: command = input('') while not valid_command: if command == 'help': print_header('Sorting algorithms') print_subheader('Bubble sorts') print_command('bubble', 'Bubble sort') print_command('cocktail', 'Cocktail shaker sort') print_command('comb', 'Comb sort') print_command('oddeven', 'Odd-even sort') print_subheader('Insertion sorts') print_command('insertion', 'Insertion sort') print_command('shell', 'Shellsort') print_command('gnome', 'Gnome sort') print_subheader('Divide and conquer') print_command('merge', 'Merge sort') print_command('quick', 'Quicksort') print_subheader('Other') print_command('selection', 'Selection sort') print_command('stooge', 'Stooge sort') print_header('Options') print_command('quit', 'Exit sortpy') print('\n') print('Click on the window after sorting finishes to select a new algorithm') command = input('\n') elif command == 'bubble': valid_command = True elif command == 'cocktail': valid_command = True elif command == 'comb': valid_command = True elif command == 'oddeven': valid_command = True elif command == 'insertion': valid_command = True elif command == 'shell': valid_command = True elif command == 'gnome': valid_command = True elif command == 'merge': valid_command = True elif command == 'quick': valid_command = True elif command == 'selection': valid_command = True elif command == 'stooge': valid_command = True elif command == 'quit': win.close() return else: print('Command not found - type help to view commands') command = input('\n') sort.playback_list.append(ds[:]) if command == 'insertion': sort.insertion_sort(ds) elif command == 'bubble': sort.bubble_sort(ds) elif command == 'cocktail': sort.cocktail_sort(ds) elif command == 'selection': sort.selection_sort(ds) elif command == 'merge': sort.merge_sort(ds, 0, sort.DATA_NUM - 1) elif command == 'quick': sort.quick_sort(ds, 0, sort.DATA_NUM - 1) elif command == 'shell': sort.shell_sort(ds) elif command == 'gnome': sort.gnome_sort(ds) elif command == 'oddeven': sort.odd_even_sort(ds) elif command == 'comb': sort.comb_sort(ds) elif command == 'stooge': sort.stooge_sort(ds, 0, sort.DATA_NUM - 1) sort.playback_list = remove_duplicates(sort.playback_list) play_animation(ds, win, bars) win.getMouse()
from sort import insertion_sort from sort import merge_sort if __name__ == "__main__": input_file = open("input.txt", "r") input_list = input_file.read().split() # get list of each number's string input_list = [int(x) for x in input_list] # change element to int input_file.close() answer = sorted(input_list) # ground truth using python's sort print("INSERTION SORT") output_insertion = insertion_sort(input_list) #print(output_insertion) assert output_insertion == answer # check if our answer is the same with python's sort print("MERGE SORT") output_merge = merge_sort(input_list) #print(output_merge) assert output_merge == answer # check if our answer is the same with python's sort output_file = open("output.txt", "w") output_file.write("{:15} | {:15}\n".format("INSERTION SORT", "MERGE SORT")) for i in range(len(input_list)): output_file.write("{:<15d} | {:<15d}\n".format(output_insertion[i], output_merge[i])) output_file.close()
def test_single_item_array(self): array = [6] self.assertEqual(merge_sort(array), array)
def test_mergesort(self): sorted_list = sort.merge_sort(self.list) self.assertTrue(self.in_order(sorted_list))
print ("я║тЯеепРсцй╠: % s" %(time.clock() - time_start) ) # ╡ЕхКеепР random.shuffle(ls) time_start = time.clock() sort.insert_sort(ls) print ("╡ЕхКеепРсцй╠: % s" %(time.clock() - time_start) ) # оё╤ШеепР random.shuffle(ls) time_start = time.clock() sort.shell_sort(ls) print ("оё╤ШеепРсцй╠: % s" %(time.clock() - time_start) ) # ╧И╡╒еепР random.shuffle(ls) time_start = time.clock() sort.merge_sort(ls) print ("╧И╡╒еепРсцй╠: % s" %(time.clock() - time_start) ) # ©ЛкыеепР random.shuffle(ls) time_start = time.clock() sort.quick_sort(ls) print ("©ЛкыеепРсцй╠: % s" %(time.clock() - time_start) ) # ╤яеепР random.shuffle(ls) time_start = time.clock() sort.heap_sort(ls) print ("╤яеепРсцй╠: % s" %(time.clock() - time_start) )
def merge_sort_test(): A = [random.randrange(0, 2 ** 10) for i in range(2 ** 20)] sort.merge_sort(A, 0, len(A) - 1)
def test_sort_odd_elements(self): array = [6, 2, 5, 8, 1, 3, 7, 4, 0] self.assertEqual(merge_sort(array), list(range(9)))
def test_repeating_el(self): main_l = [1, 2, 3, 3, 4, 5, 6, 6] for l in itertools.permutations(main_l): with self.subTest(l=l): self.assertListEqual( sort.merge_sort(list(l), order='increase'), main_l)
def test_merge_sort(array): t0 = time.time() array = sort.merge_sort(array) print "Elapsed time (merge sort recursion): " + elapsed_to_str(t0, time.time()) + " sec."
#function test from sort import fast_sort, merge_sort import time import numpy as np l1 = [] l2 = [] for i in range(40): Lis = np.random.randint(0, 10000000, 100000).tolist() strat = time.clock() print(fast_sort(Lis)[:10]) end = time.clock() l1.append(end - strat) strat = time.clock() print(merge_sort(Lis)[:10]) end = time.clock() l2.append(end - strat) e = np.array(l2) - np.array(l1) np.set_printoptions(precision=4) print('fast_sort Time cost:') print(np.array(l1)) print('merge_sort Time cost:') print(np.array(l2)) print('average (Tm - Tf)/Tf:') print(np.mean(e / np.array(l1))) print('Theoretically (Tm - Tf)/Tf :') print(0.75 / 3)
def test_case03(self): A = [3, 4, 5, 2, 1] print "origin A=%s" % A sort.merge_sort(A, 0, len(A)) print "merge sorted A=%s" % A self.assertTrue([1, 2, 3, 4, 5] == A)
def test_duplicate_value(): lst = [8, 4, 23, 42, 16, 15, 8, 23] expected = [4, 8, 8, 15, 16, 23, 23, 42] actual = merge_sort(lst) assert actual == expected
print("я║тЯеепРсцй╠: % s" % (time.clock() - time_start)) # ╡ЕхКеепР random.shuffle(ls) time_start = time.clock() sort.insert_sort(ls) print("╡ЕхКеепРсцй╠: % s" % (time.clock() - time_start)) # оё╤ШеепР random.shuffle(ls) time_start = time.clock() sort.shell_sort(ls) print("оё╤ШеепРсцй╠: % s" % (time.clock() - time_start)) # ╧И╡╒еепР random.shuffle(ls) time_start = time.clock() sort.merge_sort(ls) print("╧И╡╒еепРсцй╠: % s" % (time.clock() - time_start)) # ©ЛкыеепР random.shuffle(ls) time_start = time.clock() sort.quick_sort(ls) print("©ЛкыеепРсцй╠: % s" % (time.clock() - time_start)) # ╤яеепР random.shuffle(ls) time_start = time.clock() sort.heap_sort(ls) print("╤яеепРсцй╠: % s" % (time.clock() - time_start))
def test_unique_values(): lst = [8, 4, 23, 42, 16, 15] expected = [4, 8, 15, 16, 23, 42] actual = merge_sort(lst) assert actual == expected
print 'heap sort\n' list = sort.heap_sort(list_large[:]) assert sort.check_sorted(list) timer.get_time(time.clock()) print '' list_large = [] for i in range(50000): list_large.append(random.randint(1, 100)) print 'size:50000, for the faster ones' timer.get_time(time.clock(), False) #update time print 'merge sort\n' list = sort.merge_sort(list_large[:]) assert sort.check_sorted(list) timer.get_time(time.clock()) print '' print 'quick sort\n' list = sort.quick_sort(list_large[:]) assert sort.check_sorted(list) timer.get_time(time.clock()) print '' print 'quick sort rand\n' list = sort.quick_sort(list_large[:], rand=True) assert sort.check_sorted(list) timer.get_time(time.clock()) print ''