Пример #1
0
def main():
    """Start timer, sort, stop timer. write result to file"""
    #sizes = [10,50,100,500,1000,5000,10000,50000,100000,500000,1000000]
    b_times = []
    i_times = []
    m_times = []
    q_times = []
    size = 50000
#for size in sizes:
    for num in range(1,101):
        l = getlist("../lists/size" + str(size) + "/list" + str(num))
        start = time.time()
        bubblesort(l)
        b_times.append((size,time.time() - start))
        start = time.time()
        insertionsort(l)
        i_times.append((size,time.time() - start))
        start = time.time()
        mergesort(l)
        m_times.append((size,time.time() - start))
        start = time.time()
        quicksort(l)
        q_times.append((size,time.time() - start))
    csv = "n,bubble,insertion,merge,quick\n"
    #for size in sizes:
    for i in range(100):
        csv += str(b_times[i][0]) + ',' + str(b_times[i][1]) + ','
        csv += str(i_times[i][1]) + ',' + str(m_times[i][1]) + ','
        csv += str(m_times[i][1]) + '\n'
    f = open("size50000-python.csv", 'w')
    f.write(csv)
    f.close()
Пример #2
0
 def test_quickSort(self):
     #Test with random ints
     songs = []
     for i in range(50):
         songs.append(Song("", "", "", randint(0, 5)))
     quicksort(songs)
     for s in range(0, len(songs) - 1):
         self.assertTrue(songs[s].occ <= songs[s + 1].occ)
     #Test with identical ints
     songs2 = []
     for i in range(50):
         songs.append(Song("", "", "", 1))
     quicksort(songs)
     for s in range(0, len(songs2) - 1):
         self.assertTrue(songs2[s].occ <= songs2[s + 1].occ)
Пример #3
0
 def test_quickSort(self):
     #Test with random ints
     songs = []
     for i in range(50):
         songs.append(Song("","","",randint(0,5)))
     quicksort(songs)
     for s in range(0, len(songs)-1):
         self.assertTrue(songs[s].occ <= songs[s+1].occ)
     #Test with identical ints
     songs2 = []
     for i in range(50):
         songs.append(Song("","","",1))
     quicksort(songs)
     for s in range(0, len(songs2)-1):
         self.assertTrue(songs2[s].occ <= songs2[s+1].occ)
Пример #4
0
def quicksort(l):
	if len(l) <= 1:
		return l

	pivot = l[0].arg
	lesser = []
	greater = []

	for i in range(1, len(l)):
		x = l[i]
		if x.arg < pivot:
			lesser.append(x)
		else:
			greater.append(x)

	return quicksort(lesser) + [pivot] + quicksort(greater)
def common_items(list_x, list_y):
    """Returns a list containing all the items in x that are also in y.
    The resulting list should be in order.
    Clashes need only be listed once.
    Returns an empty list if there are none.
    >>> common_items([0,1,2,3],[0,0,2,4])
    [0, 2]
    >>> common_items([0,1,2,3],[1,2,3,4])
    [1, 2, 3]
    >>> common_items([0,1,2,3],[3,2,1,0])
    [0, 1, 2, 3]
    >>> common_items([0,1,2,3],[5,6,7,8])
    []
    >>> common_items([],[5,6,7,8])
    []
    >>> common_items([1,2,3,4],[])
    []
    >>> common_items([],[])
    []
    
    """

    common = []
    pos1 = 0
    pos2 = 0
    x = len(list_x)
    y = len(list_y)
    a = quicksort(list_x, style='Mo3-pivot')
    b = quicksort(list_y, style='Mo3-pivot')
    count = 0
    if x < 1 or y < 1:
        return common
    while pos1 < x and pos2 < y:
        first = b[pos1]
        second = a[pos2]
        count += 1
        if first == second:
            common.append(second)
            pos1 += 1
            pos2 += 1
        else:
            count += 1
            if first < second:
                pos1 += 1
            else:
                pos2 += 1
    return common, count
Пример #6
0
def main():
    """Try all of the size10 lists"""
    for i in range(1,101):
        l = getlist("../lists/size10/list" + str(i))
        assert(sorted(l) == quicksort(l))
        assert(sorted(l) == mergesort(l))
        assert(sorted(l) == bubblesort(l))
        assert(sorted(l) == insertionsort(l))
    print("done")
Пример #7
0
 def test_sort(self):
     for i in range(50):
         l = self.make_list()
         l2 = l[:]
         self.assertTrue(quicksort(l) == sorted(l2))
     for i in range(50):
         l = self.make_list()
         l2 = l[:]
         quicksort_inplace(l)
         self.assertTrue(l == sorted(l2))
Пример #8
0
def save_time(i, list):
    start = time.clock()
    time_bubble[i] = bubblesort(list[0])		# Tempo do bubblesort
    time_quick[i] = quicksort(list[1])		# Tempo do quicksort
    time_insert[i] = insertionsort(list[2])  # Tempo do insertionsort
    time_shell[i] = shellsort(list[3])		# Tempo do shellsort
    time_select[i] = selectionsort(list[4])  # Tempo do selectionsort
    time_heap[i] = heapsort(list[5])		# Tempo do heapsort
    time_merge[i] = mergesort(list[6])		# Tempo do merge
    end = time.clock()
    actualtime = end - start
    print "Tamanho de lista: {0} | Tempo para a execucao de todos algoritmos: {1}s".format(len(list[0]), actualtime)
    return  # forca a saida
Пример #9
0
 def test_left_1000(self):
     A = load1000()
     q = quicksort(A, 0, 1000, 'left')
     self.assertEqual(10297, q)
     self.assertSequenceEqual(range(1, 1001), A)
 def testQuicksorts(self):
     aLists = [[], [5], [6, 7], [2, 4, 3]]
     for aList in aLists:
         quicksort(aList)
         self.assertEquals(aList, sorted(aList[:]))
Пример #11
0
# Maxine Liu
# 10/22/2018
# COSC 1
# creates files cities_alpha.txt, cities_population.txt, and cities_latitude.txt.

from quicksort import *
from list_of_cities import *

# creates file cities_alpha.txt where city objects are ranked by instance variables self.name in the City class.

alphabetical = open("cities_alpha.txt", "w")

# sorting by city name alphabetically

City.__le__ = City.compare_name
quicksort(list_all_cities)

# deposit city objects in text with a new life for each city

for city in list_all_cities:
    alphabetical.write(str(city) + "\n")

alphabetical.close()

# creates file cities_population.txt where city objects are ranked by instance variables self.pop in the City class.

population = open("cities_population.txt", "w")

# sorting by city population in decreasing order.

City.__le__ = City.compare_population
Пример #12
0
 def sortarray(self):
     self.array = quicksort(self.array)
Пример #13
0
 def test_double_input(self):
     data = rand_list(count=2)
     quicksort(data)
     self.assertLessEqual(data[0], data[1])
Пример #14
0
 def test_zero_input(self):
     data = []
     quicksort(data)
     self.assertEqual(data, [])
 def test_sorted(self):
     original = [1, 2, 1, 2, 2, 1, 4, 1, 2, 3]
     correct = original[:]
     quicksort(original)
     self.assertListEqual(quicksort(original), sorted(correct))
Пример #16
0
 def test_quicksort2(self):
     testlist = [random.randrange(0, 10000) for _ in range(2001)]
     self.assertEqual(quicksort(testlist), sorted(testlist))
Пример #17
0
from quicksort import *


def binsearch(arr, q):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (high + low) // 2
        if arr[mid] > q:
            high = mid - 1
        elif arr[mid] < q:
            low = mid + 1
        else:
            return mid
    return -1


print(binsearch(quicksort(test, 0, (len(test) - 1)), 24))
Пример #18
0
 def test_quicksort(self):
     l = [2, 1, 6, 11, 2, 3, 2]
     quicksort(l, 0, 6)
     self.assertEqual(l, [1, 2, 2, 2, 3, 6, 11])
Пример #19
0
 def test_quicksort(self):
     testlist = [3, 4, 2, 1, 8, 7]
     self.assertEqual(quicksort(testlist), sorted(testlist))
Пример #20
0
 def test_all_same_input(self):
     single_val = rand_list(count=1)[0]
     data = [single_val]*100
     quicksort(data)
     for i in range(0, 100):
         self.assertEqual(single_val, data[i])
Пример #21
0
 def test_all_zero_input(self):
     data = [0]*100
     quicksort(data)
     for i in range(0, 100):
         self.assertEqual(data[i], 0)
Пример #22
0
 def test_array_input(self):
     data = rand_list()
     quicksort(data)
     for i in range(1, len(data)):
         self.assertLessEqual(data[i-1], data[i])
Пример #23
0
 def test_right_1000(self):
     A = load1000()
     q = quicksort(A, 0, 1000, 'right')
     self.assertEqual(10184, q)
     self.assertSequenceEqual(range(1, 1001), A)
Пример #24
0
from quicksort import *
from mergesort import *

test = [99,14,17,2,8,19,52,36,100]
print "Test array: " + str(test)
print "Mergesort: " + str(mergesort(test))
print "Quicksort: " + str(quicksort(test))
Пример #25
0
 def test_median_1000(self):
     A = load1000()
     q = quicksort(A, 0, 1000, 'median')
     self.assertEqual(8921, q)
     self.assertSequenceEqual(range(1, 1001), A)
Пример #26
0
import numpy as np
import argparse

from quicksort import *

parser = argparse.ArgumentParser()
parser.add_argument("arq_vetor",
                    help="nome do arquivo contendo o vetor de teste")
args = parser.parse_args()

# Lê o arquivo contendo o vetor e passado na linha de comando como um
# vetor do Numpy.

vet = np.loadtxt(args.arq_vetor)
quicksort(vet)
Пример #27
0
 def test_empty(self):
     self.assertTrue(quicksort([]) == [])
     self.assertTrue(quicksort([1]) == [1])
     self.assertTrue(quicksort_inplace([]) == [])
     self.assertTrue(quicksort_inplace([1]) == [1])
Пример #28
0
        window.blit(sort_image, frame)
        update_draw()


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if cursor(bubblesort_frame, bubblesort_btn, bubblesortConfig_btn):
            bubblesort(speed, listlength)
            setTitle()  # Reset
            setBoxes()
        elif cursor(quicksort_frame, quicksort_btn, quicksortConfig_btn):
            quicksort(speed, listlength)
            setTitle()  # Reset
            setBoxes()
        elif cursor(mergesort_frame, mergesort_btn, mergesortConfig_btn):
            mergesort(speed, listlength)
            setTitle()  # Reset
            setBoxes()
        elif cursor(insertionsort_frame, insertionsort_btn,
                    insertionsortConfig_btn):  # Algorithm not done
            # insertionsort()
            setTitle()  # Reset
            setBoxes()
'''
        # Cursor in bubblesort
        bubblesortChange = False
        if bubblesort_frame[0]+sortingBoxes_size_w > mouse_pos[0] > bubblesort_frame[0] and bubblesort_frame[1]+sortingBoxes_size_h > mouse_pos[1] > bubblesort_frame[1]:
 def test_random(self):
     original = [1, 4, 2, 6, 7, 8, 3]
     correct = original[:]
     quicksort(original)
     self.assertListEqual(quicksort(original), sorted(correct))
Пример #30
0
import time, random
from quicksort import *
from matplotlib import pyplot

list_of_ns = range(40, 800, 40)
n_trials = 100
avg_times_sorted = []

for n in list_of_ns:
    total_time_sorted = 0
    for i in range(n_trials):
        x = range(n)
        start = time.clock()
        s = quicksort(x, 'left-pivot')
        end = time.clock()
        time_taken = end - start
        total_time_sorted += time_taken
    avg_time_sorted = total_time_sorted / n_trials
    avg_times_sorted.append(avg_time_sorted)

pyplot.plot(list_of_ns, avg_times_sorted, 'bo')
pyplot.title("Time vs. List size, average of {0} trials".format(n_trials))
pyplot.xlabel('n')
pyplot.ylabel('Average Time per sort')
pyplot.show()
Пример #31
0
[[1988, 385000],[2004, 1380000]]]
>>> print("The house at %s was built in %d." % (prop[0], prop[4][0][0])
The house at 355 Noe Street was built in 1988.
>>> cto = ("Will Shulman", 154000, "BSCS Stanford, 1997")
>>> cto[0]
'Will Shulman'
>>> cto[2]
'BSCS Stanford, 1997'
>>> cto[1:2]
(154000,)
>>> cto[0:2]
('Will Shulman', 154000)
>>> cto[1:2] = 158000
>>> import divisors
>>> divisors.gatherDivisors(54)
[1, 2, 3, 6, 9, 18, 27]
>>> gatherDivisors(216)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'gatherDivisors' is not defined
>>> from divisors import gatherDivisors
>>> gatherDivisors(216)
[1, 2, 3, 4, 6, 8, 9, 12, 18, 24, 27, 36, 54, 72, 108]
>>> "neat"
'neat'
>>> from quicksort import quicksort
>>> quicksort([5, 3, 6, 1, 2, 9])
[1, 2, 3, 5, 6, 9]
>>> quicksort(["g", "b", "z", "k", "e", "a", "y", "s"])
['a', 'b', 'e', 'g', 'k', 's', 'y', 'z']
Пример #32
0
 def test_single_input(self):
     data = rand_list(count=1)
     data_cp = data[:]
     quicksort(data)
     self.assertEqual(data, data_cp)
Пример #33
0
    7,
    1,
    1,
    9,
    9,
    0,
    4,
    4,
    4,
    5,
    4,
    5,
    7,
    1,
]

if __name__ == "__main__":
    test_cases = {
        'Números aleatórios': any_numbers,
        'Já ordenados': already_sorted,
        'Ordem inversa': inversed,
        'Elementos repetidos': repeated
    }
    print("*******************************")
    for name, lista in test_cases.items():
        print("\nCaso de teste: {}".format(name))
        print(lista)
        quicksort(lista)
        print("\n Ordenado:")
        print(lista)
    print("*******************************")
Пример #34
0
import quicksort

print quicksort

list = [1,2,3]

quicksort(list)