def run(self): inicio=time.time() while (time.time()-inicio < 30): codigo_alarma = random.randint(0,10) MergeSort.mergesort([random.randint(0,self.tamano) for i in range(self.tamano)]) tiempo = time.time() self.obj.set_value(self.indice_lista, tiempo)
def __init__(self, master=None): self.ver = master.ver self.myFont = settings.FONT self.picDir = settings.PICTURE_DIR self.ansText = u"Ranking:\n" self.seihekiText = u"" tkinter.Frame.__init__(self, master) self.ans = tkinter.BooleanVar() self.ans.set(True) self.ansDialog = False self.array = [] self.ansArray = [] self.nextText = [] self.pack() self.makeWidget() self.alignWidget() self.idolsContainer = ac.IdolsContainer() self.tmpCont = MergeSort.readTable(settings.SORT_FILE_NAME) self.tmpCont.shuffle() self.sugCont = MergeSort.readTable(settings.SUGGEST_FILE_NAME) self.nameArray = self.tmpCont.returnNameArray() self.setNameArray(self.nameArray) self.reg = Regression.RegressionClass() self.sugRet = False
def run(self): while 1: codigo_alarma = random.randint(0, 10) MergeSort.mergesort_paralelo( [random.randint(0, self.tamano) for i in range(self.tamano)]) tiempo = time.time() self.obj.set_value(self.indice_lista, tiempo)
def isPerm(a, b): if (len(a) != len(b)): return False sortedA = ms.mergeSort(a) sortedB = ms.mergeSort(b) for i in range(0, len(a)): if (sortedA[i] != sortedB[i]): return False return True
def medicao_tempo(lista_de_entradas): times = [] for entrada in lista_de_entradas: print("\n\n", len(entrada), "Entradas \n\n") sorters = [ BubbleSortPlus(entrada[:]), BubbleSort(entrada[:]), QuickSortPF(entrada[:]), QuickSort(entrada[:]), HeapSort(entrada[:]), InsertionSort(entrada[:]), MergeSort(entrada[:]), SelectionSort(entrada[:]), ShellSort(entrada[:]) ] #MEDINDO TEMPO DE ORDENAÇÃO for sorter in sorters: start = time.time() sorter.sort() end = time.time() tempo = end - start times.append([sorter.nome, len(entrada), tempo]) print("TEMPO", sorter.nome, len(entrada), "ENTRADAS:", tempo) return times
def NormTest(self): heap = MS.Heap() self.assertEqual(heap.HeapSize, 0) self.assertEqual(heap.HeapArray, []) heap.Add(1, 101) self.assertEqual(heap.HeapSize, 1) self.assertEqual(heap.HeapArray, [101])
def runTest(fp): ''' :param fp: file pointer to read in values :return: number of right and the length of the linked list creates linked lists and runs merge sort, then checks for correct result ''' s_list = llist.LinkedList() count = AddValues(s_list,fp) s_list.head = student.MergeSort(s_list.head) a_list = llist.LinkedList() fp.seek(0,0) AddValues(a_list,fp) a_list.head = answer.MergeSort(a_list.head) right = check(s_list, a_list) # right = 0 # while s_list.head.next: # if s_list.head <= s_list.head.next: # right +=1 # s_list.head = s_list.head.next return right, count
def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) #create a test list: x = [] for i in range(300): x.append(random.randint(-100, 100)) self.sorter = MergeSort.MergeSort(x, verbose=False)
def test_D(self): """sort of single element is the same element""" #let's copy data d = [1] mysorter = MergeSort.MergeSort(d, verbose=False) mysorter.sort() self.assertEqual(mysorter.getData(), [1])
def test_C(self): """merging only changes start to end indexes""" #let's copy data d = [7, 9, 11, 23, 35, 8, 11, 22, 37, 81] self.sorter = MergeSort.MergeSort(d, verbose=False) dcopy = [7, 9, 11, 23, 35, 8, 11, 22, 37, 81] self.sorter.merge(0, 4, 2) for i in range(5, len(self.sorter.getData())): self.assertTrue(self.sorter.getData()[i] == dcopy[i])
def setNameArray(self, inArray): """ マージソートを行う際の次の名前を出すための関数。 """ self.array = inArray self.nextText = MergeSort.mergeWithoutRecWithAns( self.nameArray, self.ansArray) if len(self.nextText) == 2: self.imageConfig()
def test_sort(self): """tests if the sort works""" x = [] for i in range(300): x.append(random.randint(-100, 100)) self.sorter = MergeSort.MergeSort(x, verbose=False) self.sorter.sort() d = self.sorter.getData() for el in range(0, len(d) - 2): self.assertTrue(d[el] <= d[el + 1])
def process(clientsocket, data): #sort the data print "sorting data" array = eval(data) print 'Data received, sorting array of length ', len(array) array = MergeSort.mergesort(array) print 'Array sorted, sending data...' data = repr(array) clientsocket.sendall(data)
def nextCommand(self): """ GUIの状態を変えるための関数。 """ self.ansArray.append(self.ans.get()) #次にどの2人を比較するかを決定する。 self.nextText = MergeSort.mergeWithoutRecWithAns( self.array, self.ansArray) #もし2人が返ってきた場合は、画像を表示する。 if len(self.nextText) == 2: self.imageConfig() else: #そうでない場合(終了の場合)は、結果を表示する。 for i in range(0, len(self.nextText)): self.ansText = self.ansText + u"\tNo. %d:\t%s\n" % ( i + 1, self.nextText[i]) #文末の改行コードを消して、結果をログに保存 logging.info(self.ansText.rstrip(u"\n")) for a in self.nextText: #マージソートされた結果が返却されるため、その順序を保持して新しいコンテナに格納する。 self.idolsContainer.appendIdol( self.tmpCont.returnIdolByName(a)) self.nextButton.configure(state=tkinter.DISABLED) #回帰分析用のインスタンスに登録 self.reg.register(self.idolsContainer.returnContainer()) self.reg.normalizeCoef() #回帰分析の実行 regAns = self.reg.regression() self.seihekiText = Regression.seihekiChecker(regAns) #ログに係数を出力 logging.info(self.seihekiText) self.sugText = self.reg.returnPredict( self.sugCont.returnContainer()) #メッセージウィンドウを出す self.messageWindow() #新しい画面を出す if self.ansDialog == True: self.sugWindow = SugWindow(master=self, picDir=self.picDir, sugCont=self.sugCont, sugText=self.sugText, myFont=self.myFont, addText=self.addText, seihekiText=self.seihekiText) self.sugWindow.mainloop()
def main(): l = randomList() print("List size: ", len(l)) #BubbleSort start = time.time() BubbleSort.bubbleSort(l) end = time.time() print("BubbleSort: ", end - start) #InsertionSort start = time.time() InsertionSort.insertionSort(l) end = time.time() print("InsertionSort: ", end - start) #SelectionSort start = time.time() SelectionSort.selectionSort(l) end = time.time() print("SelectionSort: ", end - start) #ShellSort start = time.time() ShellSort.shellSort(l) end = time.time() print("ShellSort: ", end - start) #MergeSort start = time.time() MergeSort.mergeSort(l) end = time.time() print("MergeSort: ", end - start) #QuickSort start = time.time() QuickSort.quickSort(l, 0, len(l) - 1) end = time.time() print("QuickSort: ", end - start)
def MergeSortBest(self): stop = False N = 2 timerList = [] while stop is not True: A = ArrayGen.SortedArray(N) start = timer() MergeSort.MergeSort(A, 0, len(A) - 1) end = timer() timerList.append((end - start)) if N > self.Nmax: stop = True N += 1 return timerList
def calculateKNN(data_set, testing_data, k): correct = 0 for test_data in testing_data: euclidean_distances = [] for i in range(len(data_set)): e_obj = EuclidianObj( _calculateEuclideanDistance(test_data, data_set[i]), i) euclidean_distances.append(e_obj) # euclidean_distances.sort(key=lambda c: EuclidianObj.distance, reverse=False) # replace with merge sort euclidean_distances = MergeSort.MergeSort(euclidean_distances) k_points = [] for i in range(k): k_points.append(data_set[euclidean_distances[i].get_index()]) class_counts = [0, 0, 0] for point in k_points: point_class = point.get_class() if 'Iris-setosa' in point_class: class_counts[0] += 1 elif 'Iris-versicolor' in point_class: class_counts[1] += 1 elif 'Iris-virginica' in point_class: class_counts[2] += 1 print(class_counts) max_value = sys.maxsize * -1 max_index = 0 for i in range(3): if class_counts[i] > max_value: max_value = class_counts[i] max_index = i predicted_class = 0 if max_index == 0: predicted_class = 'Iris-setosa' elif max_index == 1: predicted_class = 'Iris-versicolor' else: predicted_class = 'Iris-virginica' print("predicted class:", predicted_class, "actual class: ", test_data.get_class()) if predicted_class in test_data.get_class(): correct += 1 print("KNN got ", correct, " out of ", len(testing_data)) return correct
def test_merge_sort(self): filename = 'numbers.txt' MergeSortTest.create_file(filename) obj = MergeSort.ExternalMergeSort(filename) obj.merge_sort() with open(filename, 'r') as file: i = int(-4999) line = file.readline() while line and i < 0: self.assertEqual(int(line), i) line = file.readline() i += 2 i = 0 while line and i < 0: self.assertEqual(int(line), i) line = file.readline() i += 2
def test(numElements, algo): A = [] for ele in range(0, numElements): A.append(random.randint(0, 100000)) if algo == "MergeSort": B = MergeSort.mergeSort(A) elif algo == "InsertionSort": B = InsertionSort.InsertionSort(A) isSorted = True for ele in range(0, numElements - 1): if B[ele] > B[ele + 1]: isSorted = False return isSorted
def MergeSortWorst(self): stop = False N = 2 Navg = 10 timerList = [] while stop is not True: avgTime = 0 for i in range(0, Navg): A = ArrayGen.DecreasingArray(N) start = timer() MergeSort.MergeSort(A, 0, len(A) - 1) end = timer() avgTime += (end - start) timerList.append((avgTime / Navg)) if N > self.Nmax: stop = True N += 1 return timerList
def main(): #inputList = [5, 7, 10, 4, 1, 6, 8, 3] #inputList = [3,9,12,6] #inputList = [3,18,6,12,9] #inputList = [5,4,3,2,1] inputList = [22, 41, 18, 9, 8, 7, 10] outputList = [] print('\nA entrada é: ', inputList) print('\nOrdenando com MergeSort...') MS.MergeSort(inputList.copy(), 0, len(inputList) - 1) print('\n\nA entrada é: ', inputList) print('\nOrdenando com QuickSort...') QS.QuickSort(inputList.copy(), 0, len(inputList) - 1)
def test_with_list(test_data): print('MergeSort:') start_time = int(round(time.time() * 1000)) result = MergeSort.merge_sort(test_data) duration = int(round(time.time() * 1000)) - start_time print('Duration: ' + str(duration) + 'ms') empty_target = result del result del start_time del duration print('InsertionSort:') start_time = int(round(time.time() * 1000)) result = InsertionSort.insertion_sort(test_data) duration = int(round(time.time() * 1000)) - start_time print('Duration: ' + str(duration) + 'ms') empty_target = result del result del start_time del duration print('BubbleSort:') start_time = int(round(time.time() * 1000)) result = BubbleSort.bubble_sort(test_data) duration = int(round(time.time() * 1000)) - start_time print('Duration: ' + str(duration) + 'ms') empty_target = result del result del start_time del duration print('SelectSort:') start_time = int(round(time.time() * 1000)) result = SelectSort.select_sort(test_data) duration = int(round(time.time() * 1000)) - start_time print('Duration: ' + str(duration) + 'ms') empty_target = result del result del start_time del duration
def main(): print("TEST") node: Node = Node('A') node.next = Node('B') print(str(node)) print() print("BUBBLE SORT") arr = [10, 3, 5, 12, 20, 9] BubbleSort(arr) print(arr) print() print("MERGE SORT") arr2 = [45, 12, 99, 69, 1, 13] MergeSort(arr2) print(arr2) print() print("QUICK SORT") arr3 = [45, 12, 99, 69, 1, 13] QuickSort(arr3) print(arr3) print() print("BINARY SEARCH") arr4 = [1,2,6,8,14] #print(BinarySearchRecursive(arr4, 2, 0, len(arr) - 1)) print(BinarySearchIterative(arr4, 8)) print(BinarySearchRecursive(arr4, 2, 0, len(arr4) - 1)) print() graph = { 'A': ['B', 'C', 'D', 'E'], 'B': ['A', 'C', 'G'], 'C': ['A', 'B', 'D'], 'D': ['A', 'C', 'E', 'H'], 'E': ['A', 'D', 'F'], 'F': ['E', 'G', 'H'], 'G': ['B', 'F'], 'H': ['D', 'F'] } # put neighbors in a reverse order for now graph2 = { 'A': ['E', 'D', 'C', 'B'], 'B': ['G', 'C', 'A'], 'C': ['D', 'B', 'A'], 'D': ['H', 'E', 'C', 'A'], 'E': ['F', 'D', 'A'], 'F': ['H', 'G', 'E'], 'G': ['F', 'B'], 'H': ['F', 'D'] } print("BREADTH FIRST SEARCH") bfs(graph, 'A') print() print("DEPTH FIRST SEARCH") dfs(graph2, 'A') print()
def mergeSortUnique(s): sortedList = ms.mergeSort(s) for i in range(0, len(sortedList)-1): if (sortedList[i] == sortedList[i+1]): return False return True
conn, addr = s.accept() #Accepts connection from client print 'Connected by', addr addr_list.append(addr) #Adds address to address list #Start and time distributed computing sorting process start_time = time.time() #Records start time sections = breakarray(array, procno) #splits array into sections for every client for i in range(procno - 1): #Converts array section into string to be sent arraystring = repr(sections[i+1]) conn.sendto( arraystring , addr_list[i] ) #Sends array string print 'Data sent, sorting array...' array = MergeSort.mergesort(sections[procID]) #Sorts section and stores it in array print 'Array sorted.' for i in range(procno - 1): #Receives sorted sections from each client arraystring = '' print 'Receiving data from clients...' while 1: data = conn.recv(4096) #Receives data in chunks arraystring += data #Adds data to array string if ']' in data: #When end of data is received break print 'Data received, merging arrays...' array = MergeSort.merge(array, eval(arraystring)) #Merges current array with section from client print 'Arrays merged.'
import time import random import InsertionSort, MergeSort if __name__ == "__main__": array_size = 10000 arr = random.sample(range(1, 10001), array_size) arr_2 = list(arr) start_merge = time.time() MergeSort.merge_sort(arr) end_merge = time.time() start_insertion = time.time() InsertionSort.insertion_sort(arr_2) end_insertion = time.time() print("Merge sort : %s seconds" % (end_merge - start_merge)) print("Insertion sort : %s seconds" % (end_insertion - start_insertion))
def test_merge(self): list_1 = [1, 2, 3, 8, 11, 13, 24] list_2 = [4, 5, 6, 7, 9] self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 24], MergeSort.merge(list_1, list_2))
def apply_sort(self, list_of_things): return MergeSort.merge_sort(list_of_things)
def run(self): inicio=time.time() while(time.time()-inicio < 5): MergeSort.mergesort([random.randint(0,self.tamano) for i in range(self.tamano)]) self.lista[self.indice_lista]=time.time()
#Start and time distributed computing sorting process start_time = time.time() #Records start time sections = breakarray(array, procno) #splits array into sections for every client for i in range(procno - 1): #Converts array section into string to be sent arraystring = repr(sections[i + 1]) c = conn_list[i] #conn.sendto( arraystring , addr_list[i] ) #Sends array string c.sendto(arraystring, addr_list[i]) #Sends array string print 'Data sent, sorting array...' array = MergeSort.mergesort( sections[procID]) #Sorts section and stores it in array print 'Array sorted.' for i in range(procno - 1): #Receives sorted sections from each client arraystring = '' print 'Receiving data from clients...' cc = conn_list[i] while 1: data = cc.recv(4096) #Receives data in chunks arraystring += data #Adds data to array string if ']' in data: #When end of data is received break print 'Data received, merging arrays...' array = MergeSort.merge( array,
for n in N: data = [] for i in range(n): data.append(random.randint(0, n * 10)) temp = "*" * 25 + "Input Size: " + str(n) + "*" * 25 print(temp) outputString += temp + "\n\n" print("Merge Sort: ") print("Random Order") runtime = 0 for i in range(repetition): startTime = time.time() print("Start: " + str(startTime)) mergeSort = MergeSort.MergeSort(MergeSort.ASC) sortedData = mergeSort.mergeSort(data[:]) if n < 100: print(data) print(sortedData) tempTime = time.time() - startTime print("Iteration " + str(i) + " Runtime: " + str(tempTime)) runtime += tempTime print("End: " + str(time.time())) randomSortTime = runtime / repetition print("Average Time Taken: " + str(randomSortTime)) print("Sorted Order") runtime = 0 for i in range(repetition): startTime = time.time()
merge_times = [] insertion_times = [] WC_merge_times = [] WC_insertion_times = [] #Create 11 arrays of a random size from 1000 to 100000 for x in range(11): n.append(random.randrange(1000,100000,1)) unsorted_arrays.append(make_array(n[x], 100)) sorted_arraysM = unsorted_arrays.copy() #Sort all of the arrays using merge sort and save the time taken to sort print("Merge Sort") for x in range(11): startTime = time.time() MergeSort.merge_sort(sorted_arraysM[x]) merge_times.append(time.time() - startTime) sorted_arryasI = unsorted_arrays.copy() #Sort all of the arrays using insertion sort and save the time taken to sort print("Insertion Sort") for x in range(11): startTime = time.time() InertionSort.insertion_sort(sorted_arryasI[x]) insertion_times.append(time.time() - startTime) #Store the array size and merge sort times in a pandas data frame merge_df = pd.DataFrame(list(zip(n, merge_times)), columns = ['Size', 'Merge Sort Time']) print(merge_df) #Store the array size and insertion sort times in a pandas data frame
M = Util.generateSorted(sizeList[i]) N = Util.generateReversed(sizeList[i]) O = Util.generateSmallRange(sizeList[i]) #listList = [L, M, N, O] #listNames = ['Random', 'Sorted', 'Reversed', 'SmallRange'] listList = [L, M, O] listNames = ['Random', 'Sorted', 'SmallRange'] timesList = [[], [], [], [], [], [], []] for x in range(len(listList)): #L = listList[x] L = Util.generateList(sizeList[i]) A = QuickSort.QuickSort(L) B = HeapSort.HeapSort(L) C = InsertionSort.InsertionSort(L) D = MergeSort.MergeSort(L) E = PythonSorted.PythonSorted(L) F = SelectionSort.SelectionSort(L) G = RadixSort.RadixSort(L) sortList = [A, B, C, D, E, F, G] sortNames = [ 'Quick', 'Heap', 'Insertion', 'Merge', 'Python', 'Selection', 'Radix' ] #sortList = [C] #sortNames = ['Insertion'] for j in range(len(sortList)): Start = time.time()
] #<<<<<THIS IS TO TEST THE FINAL DISPLAY WITHOUT HAVING TO WAIT A LONG TIME results = [None] * 6 time = timer.timer() #create the starting lists for x in range(0, 3): data[x] = rand.randomIntList(totals[x], 1, 999) #data set 1 #bubble sort time.startTimer() r = bubble.bubble_sort(data[0]) results[0] = time.endTimer() #merge Sort time.startTimer() r = merge.merge_sort(data[0]) results[1] = time.endTimer() #data set 2 #bubble sort time.startTimer() r = bubble.bubble_sort(data[1]) results[2] = time.endTimer() #merge Sort time.startTimer() r = merge.merge_sort(data[1]) results[3] = time.endTimer() #data set 3 #bubble sort time.startTimer()
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()) print pq pq.delMax() print pq pq.delMax() print pq
s.connect((HOST, PORT)) #Receives arraystring in chunks arraystring = '' print 'Receiving data...' while 1: data = s.recv(4096) #Receives data in chunks #print data arraystring += data #Adds data to array string if ']' in data: #When end of data is received break array = eval(arraystring) print 'Data received, sorting array... ' #Sorts the array which it is allocated array = MergeSort.mergesort(array) print 'Array sorted, sending data...' #Converts array into string to be sent back to server arraystring = repr(array) s.sendall(arraystring) #Sends array string print 'Data sent.' s.close()
import MergeSort import NumList # create a new NumList and print out contents listSize = 10000 testList = NumList.NumList(listSize) print "Pre MergeSort" for x in testList.my_list: print "\t" + repr(x) testList.my_list = MergeSort.merge_sort(testList.my_list) print "Post MergeSort" for x in testList.my_list: print "\t" + repr(x) # pass to merge to sort and print out contents