def timeAlgorithm(array, algorithm):
    if algorithm == "counting":
        start = time.time_ns()
        countingSort(array)
        end = time.time_ns()
    elif algorithm == "quick":
        start = time.time_ns()
        quickSort(array, 0, len(array) - 1)
        end = time.time_ns()
    elif algorithm == "insertion":
        start = time.time_ns()
        insertionSort(array)
        end = time.time_ns()
    elif algorithm == "merge":
        start = time.time_ns()
        mergeSort(array)
        end = time.time_ns()
    elif algorithm == "heap":
        start = time.time_ns()
        heapSort(array, 0, len(array))
        end = time.time_ns()
    elif algorithm == "intro":
        start = time.time_ns()
        introSort(array)
        end = time.time_ns()

    else:
        return 1
    return end - start
Esempio n. 2
0
def main():
	toSort = list(range(0, 21))
	fyShuffle(toSort)
	bubbleSort(toSort)
	fyShuffle(toSort)
	insertionSort(toSort)
	fyShuffle(toSort)
	mergeSort(toSort)
	fyShuffle(toSort)
	quickSort(toSort)
	fyShuffle(toSort)
	selectionSort(toSort)

	toSearch = [-16, -8, -4, -2, -1, 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
	for i in range (0, len(toSearch)):
		binarySearch(toSearch, toSearch[i] - 1)
		binarySearch(toSearch, toSearch[i])
		binarySearch(toSearch, toSearch[i] + 1)
	
	for i in range (0, len(toSearch)):
		interpolationSearch(toSearch, toSearch[i] - 1)
		interpolationSearch(toSearch, toSearch[i])
		interpolationSearch(toSearch, toSearch[i] + 1)

	toSearch = [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]
	for i in range (0, len(toSearch)):
		binarySearch(toSearch, toSearch[i] - 1)
		binarySearch(toSearch, toSearch[i])
	
	for i in range (0, len(toSearch)):
		interpolationSearch(toSearch, toSearch[i] - 1)
		interpolationSearch(toSearch, toSearch[i])
Esempio n. 3
0
def DeterministSelection(A,lenA,i):
    if lenA<5:
        sortedArray=mergeSort.mergeSort(A,lenA)
        return sortedArray[i-1]
    
####################################################################
#this compute the median. In the random selection all this block is replaced by int(random.random(0,lenA-1))
    medians_array=[]
    #round up the nomber of groups when its not an integer
    number_of_groups=int(lenA/5)
    if int(lenA/5)<lenA/5:
        number_of_groups+=1
    for k in range(0,number_of_groups):
        end=0
        if k*5+5>=lenA:
            end=lenA
        else:                                #detecting end of array
            end=k*5+5 
        sortedArray=mergeSort.mergeSort(A[k*5:end],end-k*5)
        middle=int((end-k*5)/2)
        medians_array.append(sortedArray[middle])   
    pivot=DeterministSelection(medians_array,number_of_groups,int(number_of_groups/2 ))#we get the value but we need index
    pivot=A.index(pivot)#index of pivot
    ############################################################################################################3
    position=PartitionAny(A,pivot,0,lenA-1)
    if position+1==i:
        return A[position]
    if position+1<i:
        return DeterministSelection(A[position+1:lenA],lenA-position-1,i-position-1)
    else:
        return DeterministSelection(A[0:position],position,i)
def time(a, sortname):
    time_start = time.time()

    if sortname == 'Insertion':
        insertionSort(a)
    if sortname == 'Merge':
        mergeSort(a)
    if sortname == 'Quick':
        quickSort(a)

    time_end = time.time()
    return (time_end - time_start)
Esempio n. 5
0
def startAlgorithm():
    global data
    #check which algorithm is selected
    if algoMenu.get() == 'Bubble Sort':
        bubbleSort(data, draw, speed.get())
    elif algoMenu.get() == 'Merge Sort':
        mergeSort(data, draw, speed.get())
    elif algoMenu.get() == 'Selection Sort':
        selectionSort(data, draw, speed.get())
    elif algoMenu.get() == 'Insertion Sort':
        insertionSort(data, draw, speed.get())
    elif algoMenu.get() == 'Quick Sort':
        quick_sort(data, 0, len(data) - 1, draw, speed.get())
        draw(data, ['green' for x in range(len(data))])
Esempio n. 6
0
def time(a, sortname):
    import time
    from insertionSort import insertionSort
    from mergeSort import mergeSort
    from quickSort import quickSort
    time_start = time.time()
    if sortname == 'Insertion':
        insertionSort(a)
    if sortname == 'Merge':
        mergeSort(a)
    if sortname == 'Quick':
        quickSort(a)

    time_end = time.time()
    return (time_end - time_start)
Esempio n. 7
0
def main():
    list=reader('input.txt')
    Lasers=calculateScore(list)
    Lasers=mergeSort.mergeSort(Lasers)
    pointsNeeded=int(input("Please input the number of best moves needed"))
    for i in range(pointsNeeded):
        print(Lasers[i].x,Lasers[i].y,'facing',Lasers[i].direction,' and score is ',Lasers[i].score )
Esempio n. 8
0
def sort_all(N): # num of array = 2**N
    input = read_input(N)  #读取待排序数据,input为python list
    ret = {}     #python 字典
    ret["origin"] = input   #初始数据
    
    #ret["merge_sort"][0] 存放排序结果 ret["merge_sort"][1] 存放排序所花时间,下同
    begin = time.time()
    ret["merge_sort"] = [ mergeSort(input.copy(), 0, len(input) - 1)  ]
    end = time.time()
    ret["merge_sort"].append(end - begin)

    begin = time.time()
    ret["heap_sort"]  = [   heapSort(input.copy())  ]
    end = time.time()
    ret["heap_sort"].append(end - begin)

    begin = time.time()
    ret["quick_sort"] = [   quickSort(input.copy(), 0, len(input) - 1)  ]
    end = time.time()
    ret["quick_sort"].append(end - begin)

    begin = time.time()
    ret["count_sort"] = [   countSort(input.copy(), 65536)  ]
    end = time.time()
    ret["count_sort"].append(end - begin)

    return ret
 def Test_empty_array(self):
     arr = [0]
     mergArray = mergeSort(arr)
     try:
         numpy.testing.assert_array_equal(arr, [])
         self.assertTrue(True)
     except AssertionError as error:
         self.assertTrue(False, error)
Esempio n. 10
0
 def test_one_element_array(self):
     arr = numpy.array([2])
     mergArray = mergeSort(arr)
     try:
         numpy.testing.assert_array_equal(mergArray, arr)
         self.assertTrue(True)
     except AssertionError as error:
         self.assertTrue(False, error)
Esempio n. 11
0
def getPercentile(num_list, percentile):
    if percentile < 0 or percentile > 1:
        return "Incorrect percentile provided"

    sorted_list = mergeSort(num_list)
    percentile_index = math.floor(len(sorted_list) * percentile)

    return sorted_list[percentile_index]
Esempio n. 12
0
 def test_small_array(self):
     arr = numpy.array([4, 8, 3, 9, 0, 8])
     mergeArray = mergeSort(arr)
     try:
         numpy.testing.assert_array_equal(mergeArray,
                                          numpy.array([0, 3, 4, 8, 8, 9]))
         self.assertTrue(True)
     except AssertionError as error:
         self.assertTrue(False, error)
Esempio n. 13
0
def startAlgorithm():
    global data
    if not data: return

    if(algMenu.get() == 'Bubble Sort'):
        bubbleSort(data, drawData, speedScale.get())
    elif(algMenu.get() == 'Quick Sort'):
        quickSort(data, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
    elif(algMenu.get() == 'Insertion Sort'):
        insertionSort(data, drawData, speedScale.get())
    elif(algMenu.get() == 'Selection Sort'):
        selectionSort(data, drawData, speedScale.get())
    elif (algMenu.get() == 'Heap Sort'):
        heapSort(data, drawData, speedScale.get())
    elif (algMenu.get() == 'Merge Sort'):
        mergeSort(data, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
Esempio n. 14
0
def getMedian(num_list):
    sorted_list = mergeSort(num_list)

    if len(sorted_list) % 2 == 0:
        print("Element 1: " + str(sorted_list[len(sorted_list) // 2]))
        print("Element 2: " + str(sorted_list[(len(sorted_list) // 2) + 1]))
        return (sorted_list[len(sorted_list) // 2] +
                sorted_list[(len(sorted_list) // 2) + 1]) / 2

    return sorted_list[len(sorted_list) // 2]
Esempio n. 15
0
def get_sort():
    restemp = []
    if (request.json and request.json['array']
            and isinstance(request.json['array'], list)
            and len(request.json['array']) > 0
            and len(request.json['array']) <= 10
            and isinstance(request.json['array'][0], int)
            and request.json['method']
            and request.json['method'] in ['bubble', 'merge']
            and isinstance(request.json['asc'], bool)):
        if (request.json['method'] == 'bubble'):
            bubbleSort.bubbleSort(restemp, request.json['array'],
                                  request.json['asc'])
        else:
            mergeSort.mergeSort(restemp, request.json['array'],
                                request.json['asc'])
        return jsonify({'res': restemp})

    else:
        return jsonify(
            {'res': 'Input is not valid, please input 1 up to 10 numbers'})
Esempio n. 16
0
def main():

    for i in range(10):

        arr = gen_array(i + 9)
        print("iteration: ", i + 1)
        print("before sort: ", arr)

        sort_data = mergeSort(arr)

        print("after sort:  ", sort_data)

        checkSort(sort_data)
Esempio n. 17
0
def sorting():
    """Выбор сортировки из выпадающего списка"""
    global array
    sorting_speed = 0.2  #задаем скорость демонстрации в диапазоне от 0.1 до 1
    if (selected_algorithm.get() == "Сортировка пузырьком"):
        bubbleSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка вставками"):
        insertSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка выбором"):
        selectSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка слиянием"):
        mergeSort(array, 0, len(array) - 1, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Быстрая сортировка"):
        quickSort(array, 0, len(array) - 1, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка Шелла"):
        shellSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
Esempio n. 18
0
def sort(arr,element):
	count = 0
	array = arr.copy()
	n = len(array)
	array = mergeSort(array)
	for i in range(n):
		second_integer = element - array[i]
		second_integer_index, frequency = binarySearch(array[i+1:],second_integer,1)
		if second_integer_index != -1:
			count += frequency
			#for _ in range(frequency):
				# print(f"({array[i]},{second_integer})", end = " ")

	#print(end = "\n")
	return count	
Esempio n. 19
0
def decrementCounts(hashTable):
    eightShingleVectors = list(
        filter(lambda x: (WILDCARD not in x), hashTable.keys()))
    mergeSort(eightShingleVectors, 0, len(eightShingleVectors) - 1, hashTable)

    maxShingleVectors = {}

    for shingle in eightShingleVectors:
        shingle = tuple(shingle)
        max = 0
        maxShingleVector = None

        for shingleVector in hashTable.keys():
            if isCoverVector(shingle,
                             shingleVector) and max < hashTable[shingleVector]:
                max = hashTable[shingleVector]
                maxShingleVector = shingleVector

        maxShingleVectors[shingle] = maxShingleVector

        for shingleVector in hashTable.keys():
            if isCoverVector(
                    shingle,
                    shingleVector) and maxShingleVector != shingleVector:
                aux = hashTable[shingleVector]
                aux -= hashTable[shingle]
                if aux < 0:
                    aux = 0
                hashTable[shingleVector] = aux

    keys = list(hashTable.keys()).copy()
    for shingleVector in keys:
        if hashTable[shingleVector] < THRESHOLD:
            hashTable.pop(shingleVector)

    return maxShingleVectors
Esempio n. 20
0
def timeElapsed(algoritmo, arr):
	start_time = time.time()
	comparaciones = 0
	
	if(algoritmo == "merge"):
		comparaciones = mergeSort.mergeSort(arr)
	elif(algoritmo == "quickStatic"):
		comparaciones = quickSortStaticPiv.quickSort(arr)
	elif(algoritmo == "quickAle"):
		comparaciones = quickSortRandomPiv.quickSort(arr)
	elif(algoritmo == "heap"):
		comparaciones = heapSort.heapSort(arr)
	elif(algoritmo == "bubble"):
		comparaciones = bubbleSort.bubbleSort(arr)

	elapsed_time = time.time() - start_time
	print("TamList: ", len(arr), "\tTime: ", elapsed_time, "Comps: ", comparaciones)
Esempio n. 21
0
def sortAlgo():
    global boo
    global array
    global barRec
    global epochs

    epochs = [0]
    boo = True

    try:
        size = int(sizeEntry.get())
    except:
        size = 15
    if size < 0:
        size = 1

    #change the value of the speed selected
    s = 1001 - speed.get()

    #decide the algo
    if algDropDown.get() == "Merge Sort":
        algo = mergeSort(array, 0, size - 1)
    elif algDropDown.get() == "Bubble Sort":
        algo = bubbleSort(array)
    elif algDropDown.get() == "Quick Sort":
        algo = quickSort(array, 0, size - 1)
    elif algDropDown.get() == "Insertion Sort":
        algo = insertionSort(array)
    elif algDropDown.get() == "Selection Sort":
        algo = selectionSort(array)
    elif algDropDown.get() == "Heap Sort":
        algo = heapSort(array)
    elif algDropDown.get() == "Radix Sort":
        algo = radixSort(array)

    #start animation
    anima = anim.FuncAnimation(fig,
                               func=updatePlot,
                               fargs=(barRec, epochs),
                               frames=algo,
                               interval=s,
                               repeat=False,
                               blit=False)
    anima._start()
Esempio n. 22
0
        if currNode == None:
            print('Not found')
        else:
            if currNode.value > value:
                self._find(currNode.leftChild, value)
            elif currNode.value < value:
                self._find(currNode.rightChild, value)
            else:
                print('Found')

        # Create a balanced binary search tree from sorted array
    def insertSort(self, sortedArr):
        mid = len(sortedArr) // 2
        if mid > 1:
            self.insertTree(sortedArr[mid])
            self.insertSort(sortedArr[:mid])
            self.insertSort(sortedArr[mid:])


# Create a random list of number
import random
import mergeSort as mS
key = random.sample(range(1000), 500)
mS.mergeSort(key)

list = binarySearchTree()
list.insertSort(key)
list.treePrint()
print("The tree's height is : " + str(list.height()))
list.find(932)
Esempio n. 23
0
        # Save the values into the corresponding lists
        for i in circles[0, :]:
            # draw the outer circle
            # cv2.circle(edges, (i[0], i[1]), i[2], (255, 255, 255), 2)
            # draw the center of the circle
            # cv2.circle(edges, (i[0], i[1]), 2, (255, 255, 255), 3)

            # Save the centers and radii
            listX.append(i[0])
            listY.append(i[1])
            listR.append(i[2])
            print("Edges circle center at: " + str(i[0]) + ", " + str(i[1]))

        # Sort the centers and radii
        sortedX = mergeSort(listX)
        sortedY = mergeSort(listY)
        sortedR = mergeSort(listR)

        # Find the medians
        medianX = sortedX[len(sortedX) // 2]
        medianY = sortedY[len(sortedY) // 2]
        medianR = sortedR[len(sortedR) // 2]

        # Draw/print the median circle
        cv2.circle(edges, (medianX, medianY), medianR, (255, 255, 255), 2)
        cv2.circle(edges, (medianX, medianY), 2, (255, 255, 255), 2)
        print("Median edges circle center: " + str(medianX) + ", " + str(medianY) + " with radius " + str(medianR))
        cv2.imshow("Edges Circle", edges)

    # Find circles in the motion frame
Esempio n. 24
0
#!/usr/bin/python3
import numpy as np
from bubbleSort import bubbleSort
from insertionSort import insertionSort
from quickSort import quickSort
from mergeSort import mergeSort
a = np.random.randint(0, 10000, 100)  # generate 100 random integer
print(a)
# bubbleSort(a)
# insertionSort(a)
# quickSort(a)
mergeSort(a)
print(a)
Esempio n. 25
0
data6 = data1[:]
data7 = data1[:]
data8 = data1[:]

s0 = time.clock()
data1.sort()
e0 = time.clock()
print 'The python sorted:', e0-s0

s7 = time.clock()
shellSort.shellSort(data7)
e7 = time.clock()
print 'shellSort:', e7-s7

s1 = time.clock()
mergeSort.mergeSort(data1)
e1 = time.clock()
print 'mergeSort:', e1-s1

s5 = time.clock()
quickSort.quick_sort(data5,0,len(data5))
e5 = time.clock()
print 'quick_sort:', e5-s5

s6 = time.clock()
quickSort.qSort(data6)
e6 = time.clock()
print 'qSort:', e6-s6

s3 = time.clock()
insertionSort.insertionSort(data3)
Esempio n. 26
0
 def test_SortByMerge(self):
     nums=[3,1,2,5,6,7,8,10,2,4]
     mergeSort(nums,0,len(nums)-1)
     self.assertEqual([1,2,2,3,4,5,6,7,8,10],nums);
Esempio n. 27
0
from mergeSort import mergeSort
array = [12, 3, 4, 5, 7, 3424, 6, 78, 9, 354, 0, 14, 5, 63, 232]
mergeSort(array)
print(array)


def binarySearch(arr, value):
    start = 0
    last = len(arr) - 1
    while last > start:
        mid = (last + start) // 2
        if arr[mid] > value:
            last = mid
        elif arr[mid] < value:
            start = mid + 1
        else:
            print('Found at: ' + str(mid))
            break
    if last == start:
        if arr[start] == value:
            print('Found at: ' + str(start))
        else:
            print("Not Found")


binarySearch(array, 1)
Esempio n. 28
0
__author__ = 'Andy'

import timeit

import mergeSort
import quickSort

list = [34, 7, 3, 31, 6, 8, 56, 24, 658, 9, 363, 563, 767, 34, 78, 2, 0, 1, 94]
print("mergeSort: ", mergeSort.mergeSort(list))

print(timeit.timeit('mergeSort.mergeSort(list)',
                    setup='import mergeSort;list = [34, 7, 3, 31, 6, 8, 56, 24, 658, 9, 363, 563, 767, 34, 78, 2, 0, 1, 94]',
                    number=30))

list = [34, 7, 3, 31, 6, 8, 56, 24, 658, 9, 363, 563, 767, 34, 78, 2, 0, 1, 94]
print("quickSort: ", quickSort.quickSort(list))

print(timeit.timeit('quickSort.quickSort(list)',
                    setup='import quickSort;import random;list = [34, 7, 3, 31, 6, 8, 56, 24, 658, 9, 363, 563, 767, 34, 78, 2, 0, 1, 94]',
                    number=30))
Esempio n. 29
0
 def sortMethod(self, arr):
     mergeSort(arr)
Esempio n. 30
0
#!/usr/bin/python

import mergeSort
import random
import sys

whichN = int(sys.argv[1])

N = [10**2, 10**4, 10**6, 10**8]

i = N[whichN]

randArray = [random.randint(1, 10000) for j in range(0, i)]

mergeSort.mergeSort(randArray)
Esempio n. 31
0
import numpy
import time
from mergeSort import mergeSort
from mergeSort import printArray

# random sorting
# ---------------------------------
randomTimes = numpy.zeros(100, dtype=float)
for x in range(0, 99):
    array = numpy.random.randint(0, 10000, 10000)
    start = time.clock()
    mergeSort(array)
    total = time.clock() - start
    randomTimes[x] = total
# printArray(randomTimes)

# sorted sorting
# ---------------------------------
sortedTimes = numpy.zeros(100, dtype=float)
for x in range(0, 99):
    array = numpy.random.randint(0, 1000, 10000)
    array = numpy.sort(array)
    start = time.clock()
    mergeSort(array)
    total = time.clock() - start
    sortedTimes[x] = total
# printArray(sortedTimes)

# reverse order sorting
# ---------------------------------
revTimes = numpy.zeros(100, dtype=float)
Esempio n. 32
0
import quickSort,mergeSort, heapSort, insertionSort, bubbleSort, time
from commonFunctions import createRandomLists


sortFunctions = ['quickSort.startQuickSort','mergeSort.mergeSort','heapSort.heapSort','insertionSort.insertionSort','bubbleSort.bubbleSort']

randomLists = createRandomLists(5,10)
listLengths = randomLists.keys()
listLengths = mergeSort.mergeSort(listLengths) # lol


functionTimes = {}
for function in sortFunctions:
    functionTimes[function] = {}
    for listLength in listLengths:
        list = randomLists[listLength]
        start = time.time()
        eval(function)(list)
        end = time.time()
        functionTimes[function][listLength] = end-start

#print functionTimes

print "N= "+" "*(len("insertionSort")+8),
for n in listLengths:
    print str(n)+" "*(5-len(str(n))),
print ""
for function in sortFunctions:
    print function.split(".")[0],reduce(lambda x,time:str(x)+" "+str(round(time,5)),functionTimes[function].values())

Esempio n. 33
0
def videoCallback( frame, drone, debug=False ):
    global cnt
    if isinstance(frame, tuple):
        # print("h.264 frame - (frame# = %s, iframe = %s, size = %s)" % (frame[0], frame[1], len(frame[2])))
        f.write(frame[-1])
        f.flush()
    else:
        # Initialize the frame size for drone adjustment
        if drone.frameWidth == 0:
            drone.frameWidth = numpy.size(frame, 1)
        if drone.frameHeight == 0:
            drone.frameHeight = numpy.size(frame, 0)

        # Initialize variables to compare the current frame to
        if drone.thisFrame is None:
            drone.lastFrame = frame
        else:
            drone.lastFrame = drone.thisFrame
        drone.thisFrame = frame

        # # Convert frames to grayscale and blur them
        # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # gray = cv2.GaussianBlur(gray, (21, 21), 0)
        #
        # grayLastFrame = cv2.cvtColor(drone.lastFrame, cv2.COLOR_BGR2GRAY)
        # grayLastFrame = cv2.GaussianBlur(grayLastFrame, (21, 21), 0)
        #
        # # compute the absolute difference between the current frame and the last frame
        # frameDelta = cv2.absdiff(grayLastFrame, gray)

        ret, thresh = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY)

        # Find edges after motion detection
        edges = cv2.Canny(thresh, drone.minEdgeVal, drone.maxEdgeVal)

        if drone.pictureBoolean:
            drone.pictureBoolean = False
            cv2.imwrite("saved_image.jpg", edges)

        # Find sphero using circles
        if drone.findSphero:
            # Find circles after detecting edges
            circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1.2, 5,
                                       param1=50, param2=30, minRadius=drone.minCircleRadius, maxRadius=drone.maxCircleRadius)
            # circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1.2, 10, minRadius=drone.minCircleRadius, maxRadius=drone.maxCircleRadius)

            if circles is not None:
                circles = numpy.uint16(numpy.around(circles))
                listX = []
                listY = []
                listR = []

                for i in circles[0, :]:
                    # # draw the outer circle
                    # cv2.circle(edges, (i[0], i[1]), i[2], (255, 255, 255), 2)
                    # # draw the center of the circle
                    # cv2.circle(edges, (i[0], i[1]), 2, (255, 255, 255), 3)

                    # Save the centers and radii
                    listX.append(i[0])
                    listY.append(i[1])
                    listR.append(i[2])
                    # print("Edges circle center at: " + str(i[0]) + ", " + str(i[1]))

                # Sort the centers and radii and print/draw the median
                sortedX = mergeSort(listX)
                sortedY = mergeSort(listY)
                sortedR = mergeSort(listR)

                medianX = sortedX[len(sortedX) // 2]
                medianY = sortedY[len(sortedY) // 2]
                medianR = sortedR[len(sortedR) // 2]

                drone.objectCenterX = medianX
                drone.objectCenterY = medianY

                cv2.circle(edges, (medianX, medianY), medianR, (255,255,255), 2)
                cv2.circle(edges, (medianX, medianY), 2, (255,255,255), 2)
                # print("Median edges circle center: " + str(medianX) + ", " + str(medianY) + " with radius " + str(medianR))

                drone.sinceLastSphero = 0
                drone.foundCircle = True
            else:
                # Fake a circle in the center if none found
                drone.objectCenterX = drone.frameWidth >> 1
                drone.objectCenterY = drone.frameHeight >> 1

                drone.sinceLastSphero += 1
                drone.foundCircle = False
        else:
            # Fake a circle in the center if none found
            drone.objectCenterX = drone.frameWidth >> 1
            drone.objectCenterY = drone.frameHeight >> 1
            drone.foundCircle = False

        # Find sphero using blobs
        if drone.findSphero and not drone.foundCircle:
            kernel = numpy.ones((5, 5), numpy.uint8)
            edges = cv2.dilate(edges, kernel, iterations=1)
            edges = cv2.erode(edges, kernel, iterations=1)

            params = cv2.SimpleBlobDetector_Params()

            # Filter by Circularity
            # params.filterByCircularity = True
            # params.minCircularity = 0.6

            # Filter by Area.
            # params.filterByArea = True
            # params.minArea = 16

            detector = cv2.SimpleBlobDetector_create(params)
            keypoints = detector.detect(edges)

            if keypoints is not None:
                listX = []
                listY = []
                listR = []

                for keypoint in keypoints:
                    # # draw the outer circle
                    # cv2.circle(edges, (i[0], i[1]), i[2], (255, 255, 255), 2)
                    # # draw the center of the circle
                    # cv2.circle(edges, (i[0], i[1]), 2, (255, 255, 255), 3)

                    # Save the centers and radii
                    # print point.pt[0]
                    listX.append(int(keypoint.pt[0]))
                    listY.append(int(keypoint.pt[1]))
                    listR.append(int(keypoint.size / 2))
                    # print("Edges circle center at: " + str(i[0]) + ", " + str(i[1]))
                    # print keypoint.pt

                if len(listX) > 0 and len(listY) > 0 and len(listR) > 0:
                    # Sort the centers and radii and print/draw the median
                    sortedX = mergeSort(listX)
                    sortedY = mergeSort(listY)
                    sortedR = mergeSort(listR)

                    # print sortedX
                    medianX = sortedX[len(sortedX) // 2]
                    medianY = sortedY[len(sortedY) // 2]
                    medianR = sortedR[len(sortedR) // 2]

                    drone.objectCenterX = medianX
                    drone.objectCenterY = medianY

                    cv2.circle(edges, (medianX, medianY), medianR, (255,255,255), 2)
                    cv2.circle(edges, (medianX, medianY), 2, (255,255,255), 2)
                    # print("Median edges circle center: " + str(medianX) + ", " + str(medianY) + " with radius " + str(medianR))

                    drone.sinceLastSphero = 0
                else:
                    # Fake a circle in the center if none found
                    drone.objectCenterX = drone.frameWidth >> 1
                    drone.objectCenterY = drone.frameHeight >> 1

                    drone.sinceLastSphero += 1
            else:
                # Fake a circle in the center if none found
                drone.objectCenterX = drone.frameWidth >> 1
                drone.objectCenterY = drone.frameHeight >> 1

                drone.sinceLastSphero += 1
        elif not drone.foundCircle:
            # Fake a circle in the center if none found
            drone.objectCenterX = drone.frameWidth >> 1
            drone.objectCenterY = drone.frameHeight >> 1
            drone.sinceLastSphero = 0

        cnt += 1
        cv2.imshow("Drone Video", frame)
        # cv2.imshow("Motion Detection", frameDelta)
        cv2.imshow("Threshold Edges", edges)
        cv2.imshow("Threshold", thresh)
        cv2.waitKey(1)
Esempio n. 34
0
import random
import time
from mergeSort import mergeSort

f = open("mergeTime.text","w+")

total = 0

for n in range(10000,110000,10000):
	print("The size of the array is %d" %n)
	arr = [0]* n;
	for i in range(n):
		arr[i] = random.randint(0,10000)

	start = time.clock()
	mergeSort(arr)
	seconds = time.clock() - start
	print("The time for insertion Sort is : %f" %seconds)
	total = total + seconds
	seconds = str(seconds)
	f.write(seconds+'\n')

f.close()
Esempio n. 35
0
#This file is just to compile all the feature branches

from bubblesort import bubbleSort
from mergeSort import mergeSort
from quicksort import quickSort

testBubble = [3, 10, 40, 20, 30, 4, 1]
testMerge = [100, 5, 68, 3, 1, 10]
testQuick = [4, 15, 23, 1, 11, 22]

bubbleSort(testBubble)
print("Here is the the sorted array using bubble sort")
print(testBubble)
mergeSort(testMerge)
print("Here is the sorted array using Merge sort")
print(testMerge)
quickSort(testQuick, 0, len(testQuick) - 1)
print("Here is the sorted array using quick sort")
print(testQuick)
Esempio n. 36
0
def main():
    window.fill((255, 255, 255))
    query = [random.randrange(20, 400) for i in range(100)]

    c = [135, 206, 235]
    start = 100
    i = start
    j = 0
    while i < 1000 + start:
        pygame.draw.line(window, c, (i, 500), (i, 500 - query[j]), 5)
        j += 1
        i += 10
        pygame.display.update()

    s = 80
    quick = button(mnt, 10 + s, 520, 180, 50, "quickSort")
    button.draw(quick, window)

    merge = button(mnt, 210 + s, 520, 180, 50, "mergeSort")
    button.draw(merge, window)

    selection = button(mnt, 400 + s, 520, 200, 50, "selectionSort")
    button.draw(selection, window)

    insertion = button(mnt, 610 + s, 520, 200, 50, "insertionSort")
    button.draw(insertion, window)

    bubble = button(mnt, 820 + s, 520, 200, 50, "bubbleSort")
    button.draw(bubble, window)

    speed = Slider("Speed", 0.025, 0.05, 0, 630)

    pygame.display.update()

    pause = button(mnt, 450, 520, 160, 50, "start/stop")

    run = True

    while run:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                if quick.isOver(pos):
                    clearinstruction(window, pause)
                    #message("illustrating ..quickSort",window)
                    quickSort(query, 0, 99, window, pause, speed, 0.025)
                    run = False
                elif merge.isOver(pos):
                    clearinstruction(window, pause)
                    #message("illustrating ..mergeSort",window)
                    mergeSort(query, 0, 99, window, pause, speed)
                    run = False
                elif selection.isOver(pos):
                    clearinstruction(
                        window,
                        pause)  #message("illustrating ..selectionSort",window)
                    selectionSort(query, 0, 99, window, pause, speed)
                    run = False
                elif insertion.isOver(pos):
                    clearinstruction(
                        window,
                        pause)  #message("illustrating ..insertionSort",window)
                    insertionSort(query, 0, 99, window, pause, speed)
                    run = False
                elif bubble.isOver(pos):
                    #message("illustrating ..bubbleSort",window)
                    clearinstruction(window, pause)
                    bubbleSort(query, window, pause, speed)
                    run = False
            elif event.type == pygame.QUIT:
                pygame.quit()

    clearInstruction(window)
    restart = button(mnt, 550, 520, 120, 50, "restart")
    button.draw(restart, window)
    pygame.display.update()

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and restart.isOver(
                    pygame.mouse.get_pos()):
                try:
                    main()
                except:
                    pass

    pygame.quit()