def test_none(self): array = None # one way to test for exceptions using a context manager with self.assertRaises(TypeError): insertion_sort(array) # another way to test for exceptions using a function self.assertRaises(TypeError, insertion_sort, array)
def test_best_case_insertion_sort(): data = gen_sorted_array() sorted_data = SortedList(data) insertion_sort(data) assert np.array_equal(data, sorted_data)
def test_insertion_sort_random(self): for i in range(101): a = [] for _ in range(i): a.append(random.randint(1, 10000)) s = sorted(a) sort.insertion_sort(a) self.assertEqual(a, s)
def test_insertion_sort(): for _ in range(500): r = random.randint(0, 100) arr = get_random_arr(r) arr_copy = arr[:] sort.insertion_sort(arr) assert arr == sorted(arr_copy)
def test_insertion_sort(self): # 断言空列表直接返回 self.assertEqual(sort.insertion_sort([]), []) # 断言单元素列表直接返回 self.assertEqual(sort.insertion_sort([1]), [1]) # 断言2元素列表 self.assertEqual(sort.insertion_sort([2, 1]), [1, 2]) # 断言3元素列表 self.assertEqual(sort.insertion_sort([1, 3, 2]), [1, 2, 3])
def visualize_insertion_sort(lst, vis): start_time = time.perf_counter_ns() sort.insertion_sort(lst, vis) end_time = time.perf_counter_ns() vis.replay() vis.reset() print('Insertion Sort') print(f'Time: {end_time - start_time:,}ns\n')
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_insertion_sort(): alist = range(10) random.shuffle(alist) ret = sort.insertion_sort(alist) assert ret == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def binary_search(the_list, target_value): # First, sort the list sorted_list = insertion_sort(the_list) length = len(sorted_list) # Initialize start and end variables start = 0 end = length # while length is >= 1 look for target: while length >= 1: # look for target # Find the mid point of the segment we're looking in mid = start + (length // 2) # Determine if middle value is >, <, or equal, # If statement to find out which of the three is true # If equal, we found it. Return middle if sorted_list[mid] == target_value: return (sorted_list, mid) # Elif greater than, reduce segment to to left half from middle, repeat loop elif sorted_list[mid] > target_value: length =len(sorted_list[start:mid]) end = mid # Elif less than, reduce segment to right half from middle, repeat loop elif sorted_list[mid] < target_value: length = len(sorted_list[mid + 1:end]) start = mid + 1 # If we can't find the index, return -1 # This return returns the sorted list if the index has been found # and -1 if the index wasn't found return (sorted_list, -1)
def test_insertion_sort(): assert_equal(insertion_sort([1, 2, 3]), [1, 2, 3]) assert_equal(insertion_sort([3, 2, 1]), [1, 2, 3]) assert_equal(insertion_sort([2, 1, 3]), [1, 2, 3]) assert_equal(insertion_sort([55, -4, 34, 34, 15]), [-4, 15, 34, 34, 55]) assert_equal(insertion_sort([0.4, 567, -10006, 23, 0, 5]), [-10006, 0, 0.4, 5, 23, 567]) assert_equal(insertion_sort([7]), [7]) assert_equal(insertion_sort([]), []) assert_equal(insertion_sort(None), None)
def test_insertion_sort(): print "\ninsertion sort begin" count = random.randint(100, 1000) for _ in range(count): length = random.randint(5, 30) source = tool.random_list(0, 100, length) target = sort.insertion_sort(source) if tool.list_is_ascend(target) is False: print source print target print "" assert (tool.list_is_ascend(target)) print "insertion sort success in {0} times.\n".format(count)
def q4_insertion_sort(self): try: tests = 1000 points = 0 for i in xrange(tests): l = [random() for i in xrange(randint(20, 50))] if sorted(l) == insertion_sort(l): points += 1 self.total_points += 2 return ('insertion_sort', points, tests) except: return ('No insertion sort found', 0, 0)
def graph_menu(): os.system('cls||clear') with open('disciplines.json') as f: disciplines = json.load(f) print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Estrutura de Dados 2 - Algoritmos de Ordenção O(n²)\n') print('==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n') print('Ordernar por : ' + '\n') print('[1] - Código da Matéria') print('[2] - Nome da Matéria') print('[3] - Sair') print('') print('\033[1m'+'==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==\n' + '\033[0m') param = int(input('>>>')) param = 'name' if (param > 1) else 'code' runtime = [] sort = ['Insertion Sort', 'Selection Sort', 'Bubble Sort'] start = time.time() i = insertion_sort(disciplines, param) end = time.time() runtime.append(end - start) with open('disciplines.json') as f: disciplines = json.load(f) start = time.time() i = selection_sort(disciplines, param) end = time.time() runtime.append(end - start) with open('disciplines.json') as f: disciplines = json.load(f) start = time.time() i = bubble_sort(disciplines, param) end = time.time() runtime.append(end - start) print(runtime) plt.figure(figsize=(10,5)) plt.barh(sort, runtime, color='blue') plt.xlabel('Tempo de execução') plt.show()
def test_sorted_list(self): data_size = 1000 seed(42) orig_data = sample(range(data_size * 3), k=data_size) self.assertFalse(is_sorted(orig_data)) test_data = selection_sort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = insertion_sort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = mergesort(orig_data.copy()) self.assertTrue(is_sorted(test_data)) test_data = quicksort(orig_data.copy()) self.assertTrue(is_sorted(test_data))
def test_sorted_list(): data_size = 1000 seed(42) orig_data = sample(range(data_size * 3), k=data_size) assert not is_sorted(orig_data) test_data = selection_sort(orig_data.copy()) assert is_sorted(test_data) test_data = insertion_sort(orig_data.copy()) assert is_sorted(test_data) test_data = mergesort(orig_data.copy()) assert is_sorted(test_data) test_data = quicksort(orig_data.copy()) assert is_sorted(test_data)
def graph(list_sizes=np.arange(1, 1000, 100)): bubble_time = [] sorted_time = [] quicksort_time = [] insert_time = [] for x in list_sizes: test_list = list(np.random.randint(10, size=x)) bubble_time_start = time() bubblesort(test_list) bubble_time.append(time() - bubble_time_start) sort_time_start = time() sorted(test_list) sorted_time.append(time() - sort_time_start) quicksort_time_start = time() quicksort(test_list) quicksort_time.append(time() - quicksort_time_start) insert_time_start = time() insertion_sort(test_list) insert_time.append(time() - insert_time_start) plt.loglog(list_sizes, bubble_time, '-o') plt.loglog(list_sizes, sorted_time, '-s') plt.loglog(list_sizes, quicksort_time, '-v') plt.loglog(list_sizes, insert_time, '-x') plt.xlabel('List Length') plt.ylabel('Sort Time (s)') plt.title('List Sort Time for Various Methods') plt.legend(['Bubble Sort', 'Sorted', 'Quicksort', 'Insertion Sort'], loc=2) plt.show()
def test_sort_times(self): data_size = 1000 seed(42) data = sample(range(data_size * 3), k=data_size) # selection sort test = data.copy() start = perf_counter() test = selection_sort(test) selection_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # insertion sort test = data.copy() start = perf_counter() test = insertion_sort(test) insertion_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # merge sort test = data.copy() start = perf_counter() test = mergesort(test) merge_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # quick sort test = data.copy() start = perf_counter() test = quicksort(test) quick_elapsed_time = perf_counter() - start self.assertTrue(is_sorted(test)) # tim sort test = data.copy() start = perf_counter() test.sort() tim_elapsed_time = perf_counter() - start self.assertLess(merge_elapsed_time, insertion_elapsed_time) self.assertLess(quick_elapsed_time, selection_elapsed_time) self.assertLess(tim_elapsed_time, merge_elapsed_time)
def test_sort_times(): data_size = 1000 seed(42) data = sample(range(data_size * 3), k=data_size) # selection sort test = data.copy() start = perf_counter() test = selection_sort(test) selection_elapsed_time = perf_counter() - start assert is_sorted(test) # insertion sort test = data.copy() start = perf_counter() test = insertion_sort(test) insertion_elapsed_time = perf_counter() - start assert is_sorted(test) # merge sort test = data.copy() start = perf_counter() test = mergesort(test) merge_elapsed_time = perf_counter() - start assert is_sorted(test) # quick sort test = data.copy() start = perf_counter() test = quicksort(test) quick_elapsed_time = perf_counter() - start assert is_sorted(test) # tim sort test = data.copy() start = perf_counter() test.sort() tim_elapsed_time = perf_counter() - start assert merge_elapsed_time < insertion_elapsed_time assert quick_elapsed_time < selection_elapsed_time assert tim_elapsed_time < merge_elapsed_time
def lihatkritikdansaran(wahana): #Id_wahana = input('Masukkan ID Wahana: ') # mengurutkan data secara alfabetis idwahana_terurut = insertion_sort((wahana[1::]), 2) print('Riwayat: ') #menginput Id_wahana dari kolom file ke array baru #for i in range (1000): # idwahana [i] = user[i]['id_wahana'] #idwahanaterurut = idwahana #mencari kritik dan saran sesuai wahana for i in range(CONST_VARS.N): row = idwahana_terurut[i] if (row == CONST_VARS.MARK_4): break print(row[2] + '\t|\t' + row[1] + '\t|\t' + row[0] + '\t|\t' + row[3])
def insertion_sort_test(): A = [random.randrange(0, 2 ** 10) for i in range(2 ** 20)] sort.insertion_sort(A)
def test_merge_sort(self): x = [4, 8, 2, 1, 0] self.assertEqual(insertion_sort(x), [0, 1, 2, 4, 8])
def test_insertion_sort(self): array = [7, 5, 1, 8, 3, 4, 4, 7, 3, 6, 2, 1, 8, 9, 0, 6] assert sort.insertion_sort(array) == [0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9]
def handle_insertion_sort(self): """sort with insertion_sort() function""" print(insertion_sort(self.uol))
def test_given_sequnce_and_delimiter_n_return_subsorted_seq_after_n_exchanges(): assert_equal(insertion_sort([1, 2, 7, 4, 5, 6], delimeter=1), [1, 2, 4, 7, 5, 6])
def test_insertion_sort_descending(self): data = [8, 9, 10, 7, 3, 2, 1] insertion_sort(data, True) self.assertEqual([10, 9, 8, 7, 3, 2, 1], data)
def test_case03(self): A = [3, 4, 5, 2, 1] print "origin A=%s" % A sort.insertion_sort(A) print "insertion sorted A=%s" % A self.assertTrue([1, 2, 3, 4, 5] == A)
def show_menu(): print("Welcome to bank management system by alexcarchiar") print("Version 1.0") flag = 1 while (flag != 9): print("Available functions: press the right number key") print("1 - Create account") print("2- Delete account") print("3- Search account holder") print("4- Withdraw") print("5- Deposit") print("6- Modify account") print("7- Money transfer") print("8- Show all account holders") print("9- Close program") flag = int(input("Your choice: ")) if flag == 1: print("Fill in the information") type = input("Account type: ") currency = input("Currency: ") name = input("Name: ") surname = input("Last name: ") address = input("Address: ") doc_type = input("Document type: ") doc_num = input("Document number: ") number = int(input("Account number: ")) Accounts.append( bank.Account(type, currency, name, surname, address, doc_type, doc_num, number)) sort.insertion_sort(Accounts) elif flag == 2: acc_number = int(input("Insert the account number: ")) acc = search.search(Accounts, acc_number) if acc == -1: print("The account does not exist") else: Accounts[acc].show_info() print( "Are you sure you want to delete this account? Press 1 to confirm, any other key to cancel" ) dele = int(input()) if dele == 1: del Accounts[acc] print(bank.Account.Count) else: print("Deletion cancelled") elif flag == 3: acc_number = int(input("Insert the account number: ")) acc = search.search(Accounts, acc_number) if acc == None: print("The account does not exist") else: Accounts[acc].show_info() elif flag == 4: acc_number = int(input("Insert the account number: ")) acc = search.search(Accounts, acc_number) if acc == -1: print("The account does not exist") else: print("Available balance: ", Accounts[acc].balance, " ", Accounts[acc].currency) amount = int(input("Amount to withdraw?")) Accounts[acc].withdraw(amount) elif flag == 5: acc_number = int(input("Insert the account number: ")) acc = search.search(Accounts, acc_number) if acc == -1: print("The account does not exist") else: print("Available balance: ", Accounts[acc].balance, " ", Accounts[acc].currency) amount = int(input("Amount to deposit?")) curr = input("currency?") Accounts[acc].deposit(amount, curr) elif flag == 6: pass #I can add the options to modify the various parts of the account # informations but that is just a series of if-elif...-else # and inputs so I'm just too lazy to do it elif flag == 7: acc_number = int(input("Insert the sender's account number: ")) acc1 = search.search(Accounts, acc_number) if acc1 == -1: print("The account does not exist") else: acc_number = int( input("Insert the receiver's account number: ")) acc2 = search.search(Accounts, acc_number) if acc2 == -1: print("The account does not exist") else: amount = int( input("How much money from the sender's account?")) bank.transfer(Accounts[acc1], Accounts[acc2], amount) elif flag == 8: print("Account number, name, surname") for i in range(0, len(Accounts)): print(Accounts[i].number, " ", Accounts[i].owner.name, " ", Accounts[i].owner.surname) elif flag == 9: save_data() print("Bye Bye!") else: print("Wrong input. Please try again")
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()
# UnionFind.parseUnionResult("0 7 2 5 4 5 6 7 5 9") # 2 ary = [ int(i) for i in "22 24 28 30 32 49 50 57 64 67 72 77 85 96 98".split() ] binarySearch(ary, 39, 0, 15) # 4 i = 100 for i in range(100, 100000, 10000): print i, run(i) # 7 ary = "15 31 47 50 55 75 18 49 10 80".split() sort.insertion_sort(ary, 6) # 8 ary = "80 86 11 90 84 45 14 75 85 92".split() aux = "80 86 11 90 84 45 14 75 85 92".split() MergeSort.bottom_up_merge_sort(ary, aux) # 9 ary = "38 40 93 37 77 28 36 56 89 64 46 88".split() QuickSort.parti(ary, 0, len(ary) - 1) print " ".join(ary) # 10 pq = PriorityQueue.PQ() pq.setLi("Z W R V M E F B D G".split())
def bestwahana(pembelian, wahana): pembelian = pembelian[1::] # mengurutkan csv pembelian berdasarkan ID wahana pembelian_terurut_berdasarkanID = [ CONST_VARS.MARK_4 for i in range(CONST_VARS.N) ] pembelian_terurut_berdasarkanID = insertion_sort(pembelian, 2) array_id_dan_Jumlahtiket = [CONST_VARS.MARK_3 for i in range(CONST_VARS.N)] n = i = m = 0 nama_wahana = '' id_skrg = id_sblm = pembelian_terurut_berdasarkanID[0][2] while (n < CONST_VARS.N and pembelian_terurut_berdasarkanID[n] != CONST_VARS.MARK_4): sum = 0 while (id_skrg == id_sblm and pembelian_terurut_berdasarkanID[n] != CONST_VARS.MARK_4): sum += int(pembelian_terurut_berdasarkanID[n][3]) n += 1 if (n < CONST_VARS.N and pembelian_terurut_berdasarkanID[n] != CONST_VARS.MARK_4): id_skrg = pembelian_terurut_berdasarkanID[n][2] # berikutnya else: break while (m < CONST_VARS.N): if id_sblm == wahana[m][ 0]: # akses csv wahana untuk ambil nama wahana nama_wahana = wahana[m][ 1] # akses nama wahana dari filw wahana m += 1 m = 0 array_id_dan_Jumlahtiket[i] = [id_sblm, nama_wahana, sum] if (n < CONST_VARS.N): id_skrg = id_sblm = pembelian_terurut_berdasarkanID[n][2] else: break i += 1 # Id_ygakan_dijumlahkan = pembelian_terurut_berdasarkanID[0][0] # Idwahana pertama # # Id_ygakan_dijumlahkan = pembelian_terurut_berdasarkanID[1][0] # Idwahana pertama # #menjumlahkan tiket yg terjual ke array_id_dan_Jumlahtiket berdasarkan ID wahana # for i in range (1000): # for j in range (2): # array_id_dan_Jumlahtiket[i][0] = Id_ygakan_dijumlahkan # while array_id_dan_Jumlahtiket[i][0] == Id_ygakan_dijumlahkan: # array_id_dan_Jumlahtiket[i][1] += pembelian_terurut_berdasarkanID[2][j] #dijumlahkan dengan jumlah tiket yang terjual # Id_ygakan_dijumlahkan = pembelian_terurut_berdasarkanID[j][0] #pindah ke Id wahana berikutnya untuk dicari jumlah tiket yang terjual array_id_dan_Jumlahtiket_terurut = insertion_sort(array_id_dan_Jumlahtiket, 2) # print hasil array untuk 3 wahana dengan jumlah tiket terbanyak # n = 0 # while n != 3: n = 1 for i in range(i - 1, i - 4, -1): print(str(n), end=" |\t") for j in range(3): if (j != 2): print(array_id_dan_Jumlahtiket_terurut[i][j], end="\t|\t") else: print(array_id_dan_Jumlahtiket_terurut[i][j]) n += 1
def test_insertion_sort(self): """ Test Insertion 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.insertion_sort(sample))
def test_insertion_sort(self): expected_sorted_list = [self.player2, self.player1] sorted_players = insertion_sort(self.players) for i in range(0, 2): self.assertEqual(sorted_players[i], expected_sorted_list[i])
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 b = a[:] sort.selection_sort(b) print b b = a[:] sort.bubble_sort(b) print b
def test_insertion_sort_ascending(self): data = [8, 9, 10, 7, 3, 2, 1] insertion_sort(data) self.assertEqual([1, 2, 3, 7, 8, 9, 10], data)
def choice_eight(self): """ method for sorting list with insertion_sort""" insertion_sort(self.node_list) print(self.node_list.print_list())
def test_random_insertion_sort(self): sortable = self.random_numbers sort.insertion_sort(sortable)
# UnionFind.parseUnionResult("9 0 0 0 0 4 1 4 0 5") # UnionFind.parseUnionResult("0 7 8 3 7 6 8 8 3 5") # UnionFind.parseUnionResult("0 7 2 5 4 5 6 7 5 9") # 2 ary = [int(i) for i in "22 24 28 30 32 49 50 57 64 67 72 77 85 96 98".split()] binarySearch(ary, 39, 0, 15) # 4 i = 100 for i in range(100, 100000, 10000): print i, run(i) # 7 ary = "15 31 47 50 55 75 18 49 10 80".split() sort.insertion_sort(ary, 6) # 8 ary = "80 86 11 90 84 45 14 75 85 92".split() aux = "80 86 11 90 84 45 14 75 85 92".split() MergeSort.bottom_up_merge_sort(ary, aux) # 9 ary = "38 40 93 37 77 28 36 56 89 64 46 88".split() QuickSort.parti(ary, 0, len(ary) - 1) print " ".join(ary) # 10 pq = PriorityQueue.PQ() pq.setLi("Z W R V M E F B D G".split())