예제 #1
0
def main(input_file, output_file):
    l = utils.read_input(input_file)
    sort.quicksort(l, key=lambda p: p.x)
    maximal_points = []
    sc = staircase1.Staircase2D()

    #Pdb().set_trace()
    for i in range(len(l) - 1, -1, -1):
        p = l[i]
        #if p.ind == 951:
        #    Pdb().set_trace()
        is_maximal = sc.update(point.Point2D(p.ind, p.y, p.z))
        #print(p)
        #print(sc.maximal_points.inorder_traverse())
        #if sc.size > 0:
        #    sc.maximal_points.display()

        #print('-----------------')
        if is_maximal:
            maximal_points.append(p)
    #
    sort.quicksort(maximal_points, key=lambda p: p.ind)
    fh = open(output_file, 'w')
    print(len(maximal_points), file=fh)
    for mp in maximal_points:
        print(mp.ind, file=fh)
    #
    fh.close()
예제 #2
0
def main():
    a = create_list()
    start = time.time()
    quicksort(a)
    elapsed = (time.time() - start)
    print_list(a)
    print("--Quick Sort--")
    print("Total Sort Time: ", elapsed)
    print()
    input("press enter to run next sort")
    
    a = create_list()
    start = time.time()
    bubblesort(a)
    elapsed = (time.time() - start)
    print_list(a)
    print("--Bubble Sort--")
    print("Total Sort Time: ", elapsed)
    print()
    input("press enter to run next sort")
    
    a = create_list()
    start = time.time()
    hi_low_sort(a)
    elapsed = (time.time() - start)
    print_list(a)
    print("--hi_low Sort--")
    print("Total Sort Time: ", elapsed)
    input("press enter to end")
def test_quicksort():
    for _ in range(500):
        r = random.randint(0, 100)
        arr = get_random_arr(r)
        arr_copy = arr[:]

        sort.quicksort(arr, 0, len(arr) - 1)
        assert arr == sorted(arr_copy)
예제 #4
0
 def testQuickSort4(self):
     l = list()
     random.seed(12345)
     l.extend(random.sample(xrange(1000), 900))
     l.extend(random.sample(xrange(1000), 900))
     l.extend(random.sample(xrange(1000), 900))
     ol = l[:]
     sort.quicksort(l)
     self.assertEqual(l, sorted(ol))
예제 #5
0
def read_file(filename):
    """
    Read a csv file containing list of chess players
    and return a sorted list using quicksort

    :param filename: csv file path ('chess-players.csv')
    :return: list: list of players read from file
    """
    # empty list that will hold list of players
    list = []

    with open(filename, mode='r', encoding='utf-8') as f:
        reader = csv.DictReader(f, quotechar='"', quoting=csv.QUOTE_ALL, skipinitialspace=True)
        for row in reader:
            last_name = row['Last name']
            first_name = row['First name']
            full_name = row['Full name']
            countries = row['Countries'].split(',')
            dob = row['born']
            died = row['died']
            player = Player(first_name, last_name, full_name, countries, dob, died)
            list.append(player)

    # return a list of chess player that has been sorted using quicksort
    return quicksort(list)
예제 #6
0
파일: cercles.py 프로젝트: Voyager2718/Docs
def new_draw(l):
    """
    
    :param l: nouvelle liste
    :type l : list
    :return: 
    """
    n=soddy_f(l)[0]
    n2=sort.quicksort (n,sort.compare_circle)
    if n2[0][2]<=4:
        return []
    else:
        return n2+new_draw(soddy_f(l)[1])
예제 #7
0
  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))
예제 #8
0
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)
예제 #9
0
파일: main.py 프로젝트: AltumSpatium/Labs
def main():
    parser = createParser()
    argument = parser.parse_args(sys.argv[1:])
    try:
        if argument.task == 1:
            if argument.subtask == 1:
                with open(argument.file, 'r') as file:
                    text.repeats(file)
            elif argument.subtask == 2:
                with open(argument.file, 'r') as file:
                    text.average(file)
            elif argument.subtask == 3:
                with open(argument.file, 'r') as file:
                    text.median(file)
            elif argument.subtask == 4:
                with open(argument.file, 'r') as file:
                    text.top(file)
        elif argument.task == 2:
            if argument.subtask == 1:
                lst = raw_input("Enter list: ").split()
                lst = [int(elem) for elem in lst]
                print sort.quicksort(lst)
            elif argument.subtask == 2:
                lst = raw_input("Enter list: ").split()
                lst = [int(elem) for elem in lst]
                print sort.mergesort(lst)
            elif argument.subtask == 3:
                lst = raw_input("Enter list: ").split()
                lst = [int(elem) for elem in lst]
                print sort.radixsort(lst)
        elif argument.task == 3:
            storage.storage()
        elif argument.task == 4:
            n = int(raw_input("Enter n: "))
            fib.print_fib(n)
    except Exception as e:
        print e
예제 #10
0
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()
예제 #11
0
def go():
    global g_type
    global var
    global N
    global bar_plot
    global start_fig
    global ax
    lst = [x + 1 for x in range(N)]
    random.seed(123)
    random.shuffle(lst)

    if var.get() == "b":
        title = "Bubble sort"
        generator = sort.bubblesort(lst)
    elif var.get() == "i":
        title = "Insertion sort"
        generator = sort.insertionsort(lst)
    elif var.get() == "q":
        title = "Quicksort"
        generator = sort.quicksort(lst, 0, N - 1)
    else:
        title = "Selection sort"
        generator = sort.selectionsort(lst)

    ax.set_title(title)
    ax.set_xlim(0, N)
    ax.set_ylim(0, int(1.07 * N))

    text = ax.text(0.02, 0.95, "", transform=ax.transAxes)

    iteration = [0]

    def update_fig(lst, rects, iteration):
        for rect, val in zip(rects, lst):
            rect.set_height(val)
        iteration[0] += 1
        text.set_text("# of operations: {}".format(iteration[0]))

    anim = animation.FuncAnimation(start_fig,
                                   func=update_fig,
                                   fargs=(bar_plot, iteration),
                                   frames=generator,
                                   interval=1,
                                   repeat=False)
    start_fig.canvas.draw()
예제 #12
0
  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)
예제 #13
0
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
예제 #14
0
 def testQuickSort(self):
     l = [2, 3, 1]
     sort.quicksort(l)
     self.assertEqual(l, [1, 2, 3])
예제 #15
0
def find_min(collection):
    global glob_min, pair_1, pair_2
    #Sort points according to 1st coordinate
    collection = sort.quicksort(collection, 0)
    if len(collection) == 1:
        return 99999999
    elif len(collection) == 2:
        if distance(collection[0], collection[1]) < glob_min:
            glob_min = distance(collection[0], collection[1])
            pair_1 = collection[0]
            pair_2 = collection[1]
        return distance(collection[0], collection[1])
    else:
        #Divide points in 2 parts
        vertical_line = collection[len(collection) // 2][0]
        min_distance = min(find_min(collection[:len(collection)//2]), \
                           find_min(collection[len(collection)//2:]))
        #Conquer the 2 divided parts
        strip = []
        for element in collection:
            if vertical_line - min_distance < element[0] < vertical_line:
                strip.append(element)
            elif vertical_line <= element[0] < vertical_line + min_distance:
                strip.append(element)
        #Sort strip by 2nd co-ordinate
        strip = sort.quicksort(strip, 1)
        """2 loops with time complexity O(n) and O(1) to find closest points in
        the given strip[]. Since the strip is sorted according to 2nd coordinate,
        all points have an upper bound on min_distance with other points.
        It can be proven geometrically that the maximum number of points outside
        min_distance of a given point in a strip will be:
        -> 8 for 2 dimension (outside a circle of radius min_distance)
        -> 43 for 3 dimension (outside a sphere of radius min_distance)
        -> 198 for 4 dimension (outside a hyper sphere of radius min_distance)
        Hence the inner loop will run for 198 times.        
        For proof on the reasoning , visit the link below:
        "http://euro.ecom.cmu.edu/people/faculty/mshamos/1976ShamosBentley.pdf".."""
        for i in range(len(strip)):
            if (i + 198 < len(strip)):
                for j in range(i + 1, i + 198):
                    if  strip[j][1] - min_distance < strip[i][1] <= strip[j][1] + min_distance \
                    and strip[j][2] - min_distance < strip[i][2] <= strip[j][2] + min_distance \
                    and strip[j][3] - min_distance < strip[i][3] <= strip[j][3] + min_distance \
                    and distance(strip[i], strip[j]) < min_distance:
                        min_distance = distance(strip[i], strip[j])
                        if distance(strip[i], strip[j]) < glob_min:
                            glob_min = distance(strip[i], strip[j])
                            pair_1 = strip[i]
                            pair_2 = strip[j]
            else:
                for j in range(i + 1, len(strip)):
                    if  strip[j][1] - min_distance < strip[i][1] <= strip[j][1] + min_distance \
                    and strip[j][2] - min_distance < strip[i][2] <= strip[j][2] + min_distance \
                    and strip[j][3] - min_distance < strip[i][3] <= strip[j][3] + min_distance \
                    and distance(strip[i], strip[j]) < min_distance:
                        min_distance = distance(strip[i], strip[j])
                        if distance(strip[i], strip[j]) < glob_min:
                            glob_min = distance(strip[i], strip[j])
                            pair_1 = strip[i]
                            pair_2 = strip[j]
        return min_distance
예제 #16
0
        # filename = "N_1E{:n}.png".format(potega)
        # plt.savefig(filename)


if __name__ == "__main__":
    lista = lists.random_integer_list
    wyniki = []
    ILOSC_PROBEK = 3

    # Quicksort, Mergesort i Timsort
    for N in [10**2, 10**3, 10**4, 10**5, 10**6]:
        czas_mergesort = timeit.timeit(
            lambda: sort.mergesort(lista(N), 0, N - 1),
            number=ILOSC_PROBEK) / ILOSC_PROBEK
        czas_quicksort = timeit.timeit(
            lambda: sort.quicksort(lista(N), 0, N - 1),
            number=ILOSC_PROBEK) / ILOSC_PROBEK
        czas_timsort = timeit.timeit(lambda: lista(N).sort(),
                                     number=ILOSC_PROBEK) / ILOSC_PROBEK
        wyniki.append({"name": "quicksort", "N": N, "time": czas_quicksort})
        wyniki.append({"name": "mergesort", "N": N, "time": czas_mergesort})
        wyniki.append({"name": "timsort", "N": N, "time": czas_timsort})

    # Selectsort, Insertsort, Bubblesort, Shakersort i Shellsort
    for N in [10**2, 10**3, 10**4]:
        czas_selectsort = timeit.timeit(
            lambda: sort.selectsort(lista(N), 0, N - 1),
            number=ILOSC_PROBEK) / ILOSC_PROBEK
        czas_insertsort = timeit.timeit(
            lambda: sort.insertsort(lista(N), 0, N - 1),
            number=ILOSC_PROBEK) / ILOSC_PROBEK
예제 #17
0
def test_quicksort_large():
    array = [random.random() for _ in range(100000)]
    a_quicksort = quicksort(array)
    a_baseline = sorted(array)

    assert a_baseline == a_quicksort, 'not sorted\n{0}'.format(a_quicksort)
예제 #18
0
        "C": 2,
        "D": 3,
        "E": 4,
        "F": 5,
        "G": 6,
        "H": 7,
        "I": 8
    }
    books = [[] for i in CATS]

    for name in os.listdir(PATH_IN):
        if name.endswith(".txt") and name[0] in CATS and name[1] == "_":
            add_books(PATH_IN + name, books)

    for i in CATS:
        sort.quicksort(books[mapping[i]], 0, len(books[mapping[i]]) - 1)

    with open(PATH_OUT + "!_white_list.txt", "w") as out:
        for i in CATS:
            out.write("-----------------------------\n")
            if i == "A":
                out.write(u"Преса:".encode("utf-8"))
            elif i == "B":
                out.write(u"Релігійна література:".encode("utf-8"))
            elif i == "C":
                out.write(u"Професійно-популярна література:".encode("utf-8"))
            elif i == "D":
                out.write(u"«Естетичні інформативні» тексти:".encode("utf-8"))
            elif i == "E":
                out.write(u"Адміністративні документи:".encode("utf-8"))
            elif i == "F":
예제 #19
0
def test_quicksort(seq):
    assert_unsorted(seq)
    assert_sorted(quicksort(seq))
예제 #20
0
def test_quicksort_sorted():
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    a_quicksort = quicksort(array)
    a_baseline = sorted(array)

    assert a_baseline == a_quicksort, 'not sorted\n{0}'.format(a_quicksort)
예제 #21
0
 def testQuickSort3(self):
     ol = range(-50, 50)
     l = sorted(ol)
     sort.quicksort(l)
     self.assertEqual(l, ol)
예제 #22
0
 def testQuickSort2(self):
     l = [2, 3, 1, 7, 8, 1 , 8 , 8, 2, 1 ,7]
     sort.quicksort(l)
     self.assertEqual(l, [1, 1, 1, 2, 2, 3, 7, 7, 8, 8, 8])
예제 #23
0
def test_quicksort(seq):
    assert_unsorted(seq)
    assert_sorted(quicksort(seq))
예제 #24
0
 def test_quicksort(self):
     for _ in range(500):
         raw_array = [round(random.random(), 2) for n in range(100)]
         default_sort = sorted(raw_array)
         sorted_array = quicksort(raw_array)
         self.assertEqual(sorted_array, default_sort)
예제 #25
0
 def testQuickSortWithManyDuplicates(self):
     ol = range(-50, 50)
     ol.extend(ol)
     l = ol[:]
     sort.quicksort(l)
     self.assertEqual(l, sorted(ol))
예제 #26
0
import random


sorted_list = [x for x in range(1,500)]
not_sorted_list = [x for x in range(500,0,-1)]
equal_list = 500*[1]

rnd = random.sample(range(1, 1001), 1000)

t1_bubble = timeit ( str(bubblesort(sorted_list)) , number =1 , globals = globals ())
t2_bubble = timeit ( str(bubblesort(not_sorted_list)) , number =1 , globals = globals ())
t3_bubble = timeit ( str(bubblesort(equal_list)) , number =1 , globals = globals ())
t4_bubble = timeit ( str(bubblesort(rnd)) , number =1 , globals = globals ())


t1_quicksort = timeit ( str(quicksort(sorted_list)) , number =1 , globals = globals ())
t2_quicksort = timeit ( str(quicksort(not_sorted_list)) , number =1 , globals = globals ())
t3_quicksort = timeit ( str(quicksort(equal_list)) , number =1 , globals = globals ())
t4_quicksort = timeit ( str(quicksort(rnd)) , number =1 , globals = globals ())

print("lista uporzadkowana")
print("bubble: ",t1_bubble)
print("quick: ",t1_quicksort)

print("lista malejąca")
print("bubble: ",t2_bubble)
print("quick: ",t2_quicksort)

print("lista stalych elementow")
print("buuble: ",t3_bubble)
print("quick: ",t3_quicksort)
예제 #27
0
if __name__ == '__main__':

    CATS = "ABCDEFGHI"
    PATH_IN = "../data/good/"
    PATH_OUT = "../aux/"

    mapping = {"A":0, "B":1, "C":2, "D":3, "E":4, "F":5, "G":6, "H":7, "I":8}
    books = [[] for i in CATS]

    for name in os.listdir(PATH_IN):
        if name.endswith(".txt") and name[0] in CATS and name[1] == "_":
            add_books(PATH_IN + name, books)

    for i in CATS:
        sort.quicksort(books[mapping[i]], 0, len(books[mapping[i]]) - 1)

    with open(PATH_OUT + "!_white_list.txt", "w") as out:
        for i in CATS:
            out.write("-----------------------------\n")
            if i == "A":
                out.write(u"Преса:".encode("utf-8"))
            elif i == "B":
                out.write(u"Релігійна література:".encode("utf-8"))
            elif i == "C":
                out.write(u"Професійно-популярна література:".encode("utf-8"))
            elif i == "D":
                out.write(u"«Естетичні інформативні» тексти:".encode("utf-8"))
            elif i == "E":
                out.write(u"Адміністративні документи:".encode("utf-8"))
            elif i == "F":
예제 #28
0
 def test_Quicksort(self):
     lst2 = [5, 4, 6, 8, 10, 2, 7, 1, 9, 3]
     self.assertEqual(sort.quicksort(lst2), [y for y in range(1, 11)])
예제 #29
0
    def test_quicksort(self):
        expected = [self.player3, self.player4, self.player2, self.player1]
        sorted_list = quicksort(self.test_players)

        for i in range(0, 3):
            self.assertEqual(sorted_list[i], expected[i])
예제 #30
0
def test_quicksort_empty():
    array = []
    a_quicksort = quicksort(array)
    a_baseline = sorted(array)

    assert a_baseline == a_quicksort, 'not sorted\n{0}'.format(a_quicksort)
예제 #31
0
	def testQuick(self):
		test_vec = self.test_vec()
		sort.quicksort(test_vec, 0, len(test_vec) - 1)
		self.assertEqual(test_vec, sorted(self.test_vec()))
예제 #32
0
def test_quicksort_reverse():
    array = [9, 8, 7, 6, 5, 4, 3, 2, 1]
    a_quicksort = quicksort(array)
    a_baseline = sorted(array)

    assert a_baseline == a_quicksort, 'not sorted\n{0}'.format(a_quicksort)
예제 #33
0
import sort
import random

lyst = [1, 3, 2, 4, 7, 6, 5]
print(lyst)
sort.selectionSort(lyst)
print(lyst)
lyst = [1, 3, 2, 4, 7, 6, 5]
print(lyst)
sort.bubbleSort(lyst)
print(lyst)
lyst = [1, 3, 2, 4, 7, 6, 5]
print(lyst)
sort.insertionSort(lyst)
print(lyst)

lyst = []
for count in range(1000):
    lyst.append(random.randint(1, 200))
print(lyst)
sort.quicksort(lyst)
print(lyst)
예제 #34
0
import sort
import sys

if not sys.argv[1:]:
    print "Usage : python sort.py argv1 argv2 ..."
    exit()
for a in range(len(sys.argv[1:])):
    try:
        sys.argv[a + 1] = int(sys.argv[a + 1])
    except:
        print "input error"
        exit()

print "quicksort"
print sort.quicksort(sys.argv[1:])
print "\nbubblesort"
print sort.bubble_sort(sys.argv[1:])
예제 #35
0
파일: est_sort.py 프로젝트: Thoth19/Sorts
import random
import argparse
import sort

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(nargs='?', type=int, default=1000, dest='number')
    args = parser.parse_args()
    lst = []
    for i in range(args.number):
        lst.append(random.randint(1,100))

    ans = sort.samplesort(list(lst))
    qs  = sort.quicksort(list(lst))
    ms  = sort.mergesort(list(lst))
    bs  = sort.bubblesort(list(lst))
    ins = sort.insertionsort(list(lst))
    sel = sort.selectionsort(list(lst))  
    
    print "Sample sort returns {} in {}".format(ans[0], ans[1])
    print "Quicksort matches sample: {} in {}".format(ans[0] == qs[0], qs[1])
    print "Mergesort matches sample: {} in {}".format(ans[0] == ms[0], ms[1])
    print "Bubblesort matches sample: {} in {}".format(ans[0] == bs[0], bs[1])
    print "Insertionsort matches sample: {} in {}".format(ans[0] == ins[0], ins[1])
    print "Selectionsort matches sample: {} in {}".format(ans[0] == sel[0], sel[1])
예제 #36
0
 def test_quicksort(self):
     x = [4, 8, 2, 1, 0]
     self.assertEqual(quicksort(x), [0, 1, 2, 4, 8])
예제 #37
0
def quicksort(elements):
    return sort.quicksort(elements)