Exemple #1
0
def main():
    '''
    l = ['apple','big','cat','dog']
    #f = lambda x:part(x,2)
    f = partial(part,16,8)
    f_letter = lambda x: x[0]
    print(f())
    gen = s()
    for key in gen:
        print(key,'\t')
    for letter, name in itertools.groupby(l,f_letter):
        print(letter,list(name))
    for x in map(f_letter,l):
        print(x)
    path_fr('test.txt')
    '''
    #np_fun()
    t = test('hello')
    t()
    print(t)
    f = F()
    l = [1, 2, 45, 4, 1, 3, 2, 6, 77, 5]
    print(l)
    quickSort(l, 0, len(l) - 1)
    linklist_fun()
    pd_fun()
Exemple #2
0
def flaskLogin():
    if not request.json or not 'UnsortedList' in request.json:
        abort(400)
    else:
        array = request.json['UnsortedList']
        sort.quickSort(array, 0, len(request.json['UnsortedList']) - 1)
        return jsonify({'sortedList': array})
def findNode(valList):
    sort.quickSort(valList)  #按值大小快速排序
    flag = valList[0][1]  #记录第一项的Class的值
    nodeList = []  #候选的节点列表
    bestNode = -1  #记录最优节点的序号,初始化为负
    bestNodeInfo = -1  #记录最优节点的infoGain值,初始化为负
    index = 0  #记录节点序号
    count = len(valList)
    for each in valList:  #each格式为[featureValue,classValue]
        if each[1] != flag:
            flag = each[1]
            nodeList.append(index)
        index += 1
    if nodeList == None:  #不存在节点返回All
        return 'All'
    for node in nodeList:  #遍历节点,求每个节点的infoGain
        leftList = valList[:node]
        rightList = valList[node:]
        infoGain = calcEntropy(leftList) * node / count + calcEntropy(
            rightList) * (count - node) / count
        #节点的infoGain值
        #print(str([valList[node-1][0],valList[node][0]])+":"+str(infoGain))
        if infoGain > bestNodeInfo:
            bestNodeInfo = infoGain
            bestNode = node
    return [valList[bestNode - 1][0], valList[bestNode][0]]
 def sortList(self, myList):
     if (self.sortingAlg == 'Bubble Sort'):
         bubbleSort(myList, delay=self.sleepTime)
     elif (self.sortingAlg == 'Merge Sort'):
         mergeSort(myList, delay=self.sleepTime)
     elif (self.sortingAlg == 'Quick Sort'):
         quickSort(myList, delay=self.sleepTime)
     self.buttons[1].setText('Start')
     self.sorting = False
Exemple #5
0
def playtime(toys):
    print("\n==SUBMENU=======================================\n" +
          " (1) Name                     (Bubble Sort)\n" +
          " (2) Height                   (Merge Sort)\n" +
          " (3) Species                  (Insertion Sort)\n" +
          " (4) First Movie Appearance   (Selection Sort)\n" +
          " (5) Number of Feet           (Quick Sort)\n" +
          "================================================\n")
    command_check = False

    while command_check == False:  #This loop checks if the input is valid
        command = int(input("Enter command number(1-5): "))
        if command in range(1, 6):
            command_check = True
    if command == 1:
        toys = sort.BubbleSort(toys)
    elif command == 2:
        toys = sort.mergeSort(toys)
    elif command == 3:
        toys = sort.InsertionSort(toys)
    elif command == 4:
        toys = sort.SelectionSort(toys)
    elif command == 5:
        toys = sort.quickSort(toys, 0, len(toys) - 1)
    print(sort.display(toys))
    return toys
Exemple #6
0
def main():
    list1 = []

    num = input("\t欢迎使用排序演示程序\n" + "请输入你想要产生的随机数个数:")
    for i in range(int(num)):
        list1.append(int(random.random() * 100))

    length = len(list1)

    print("\n=========排序方法选择==========\n" + "1.插入排序		2.折半插入排序\n" +
          "3.希尔排序		4.冒泡排序   \n" + "5.快速排序		6.直接选择排序\n" +
          "7.堆排序			8.基数排序    \n")
    fun = input("请输入你想要使用的排序函数:")

    if int(fun) < 1 or int(fun) > 8:
        print("没有这个排序函数,请重新选择")
        time.sleep(3)
        os.system("clear")
        main()
    elif fun == '1':
        st.insertSort(list1, length)
    elif fun == '2':
        st.binaryInsertSort(list1, length)
    elif fun == '3':
        st.shellSort(list1, length)
    elif fun == '4':
        st.bubbleSort(list1, length)
    elif fun == '5':
        st.quickSort(list1, 0, length - 1)
    elif fun == '6':
        st.directSelectSort(list1, length)
    elif fun == '7':
        st.heapSort(list1, length)
    elif fun == '8':
        st.radixSort(list1)

    print("\n---------------------------分割线--------------------------\n")
    main()
def quickSortTime():

    SETUP_CODE = '''
import sort
import random
testList = []
for i in range(50000):
    testList.append(random.randint(0,1000))'''

    TEST_CODE = '''
sort.quickSort(testList)'''

    times = timeit.repeat(setup=SETUP_CODE, stmt=TEST_CODE, repeat=1, number=1)

    print('quickSortTime: {}'.format(min(times)))
Exemple #8
0
#! /etc/bin/python3

import sort

List1 = [1,2,46,26,357,15]

result1 = sort.InsertSort(List1)
print(result1)

result2 = sort.mergeSort(List1)
print(result2)

result3 = sort.bucketSort(List1)
print(result3)

result4 = sort.quickSort(List1,0,len(List1)-1)
print(result4)
            print(testList)
    else:
        testList = []
        for i in range(int(sys.argv[2])):
            testList.append(random.randint(0, 10000))
        sort.iterativeMergeSort(testList)
        print("LIST SORTED")

elif sys.argv[1] == "QuickSort":
    if len(sys.argv) > 3:
        if sys.argv[3] == "PRINT":
            testList = []
            for i in range(int(sys.argv[2])):
                testList.append(random.randint(0, 10000))
            print(testList, "\n")
            sort.quickSort(testList)
            print(testList)
    else:
        testList = []
        for i in range(int(sys.argv[2])):
            testList.append(random.randint(0, 10000))
        sort.quickSort(testList)
        print("LIST SORTED")

elif sys.argv[1] == "ShellSort":
    if len(sys.argv) > 3:
        if sys.argv[3] == "PRINT":
            testList = []
            for i in range(int(sys.argv[2])):
                testList.append(random.randint(0, 10000))
            print(testList, "\n")
Exemple #10
0
    res.append(copy.copy(data))


start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    insertSort(temp)
    if temp != baseData:
        print("Insertion Sort issue")
print("Insertion sort takes on average {:.5f}".format((time.clock()-start)/num))


start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    quickSort(temp)
    if temp != baseData:
        print("Quick Sort issue")
print("Quick sort takes on average {:5f}".format((time.clock()-start)/num))


start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    rquickSort(temp)
    if temp != baseData:
        print("Random Quick Sort issue")
print("Random Quick sort takes on average {:5f}".format(
    (time.clock()-start)/num))

start = time.clock()
Exemple #11
0
        startTime = time.time()
        sort.inSort(x)
        endTime = time.time()
        insertion.append(endTime - startTime)

    for i in range(sampleSize):
        x = random.sample(range(99990), 10000)
        startTime = time.time()
        sort.merSort(x)
        endTime = time.time()
        merging.append(endTime - startTime)

    for i in range(sampleSize):
        x = random.sample(range(99990), 10000)
        startTime = time.time()
        sort.quickSort(x)
        endTime = time.time()
        quicking.append(endTime - startTime)

    for i in range(sampleSize):
        inserTime += insertion[i]
        merTime += merging[i]
        quickTime += quicking[i]

    inserTime = inserTime / sampleSize
    merTime = merTime / sampleSize
    quickTime = quickTime / sampleSize

    print("Insertion sort averaged " + str(inserTime) + " seconds")
    print("Merge sort averaged " + str(merTime) + " seconds")
    print("Quick sort averaged " + str(quickTime) + " seconds")
Exemple #12
0
import sort as st
import simplesort as simplest
import parser as ps
import algo

result = ps.parse("videos_worth_spreading.in")
videoSize = result[0]
endpointLatency = result[1]
videoRequestByEndpoint = result[2]
V = result[3]
E = result[4]
R = result[5]
C = result[6]
X = result[7]

endpointLatencyAsc = [[]]
for i in range(len(endpointLatency)):
    endpointLatencyAsc.append(simplest.quickSort(endpointLatency[i]))

endpointLatencyAsc.pop(0)

videoRequestDesc = list(reversed(st.quickSort(videoRequestByEndpoint)))

result = algo.algo(videoSize, endpointLatency, videoRequestByEndpoint,
                   videoRequestDesc, endpointLatencyAsc, V, E, R, C, X)

ps.output(result)
Exemple #13
0
import sort
import numpy as np
import time
import find

a = 99
numarray = np.random.randint(10000, size=a)
num = numarray.tolist()
start1 = time.clock()
sort.quickSort(num, 0, a - 1)
end1 = time.clock()

start2 = time.clock()
sort.quickSortr(num, 0, a - 1)
end2 = time.clock()

print("01 quicksort use " + str(end1 - start1) + "s.")
print("02 quicksortr use " + str(end2 - start2) + "s.")
sort.printnum()

list = [1, 2, 3, 4, 5, 6, 7, 8]
item = 6
res = find.binFind(list, item)
if res == False:
    print("item " + str(item) + " is not in the list.")
else:
    print("item " + str(item) + " is in the list.")
Exemple #14
0
# -*- coding:utf-8 -*-
import random

from sort import (bubbleSort, bubbleSort2, selectionSort, insertSort,
                  shellSort, shellSort2, mergeSort, quickSort, quickSort2)

if __name__ == '__main__':
    test_list = [random.randrange(0, 1000) for i in range(100000)]
    # test_list = [305, 456, 833, 758, 348, 370, 416, 333, 356, 19]
    test_list
    # 复制一份test_list 传给排序函数,可使用list, [:]或copy方法
    # print bubbleSort(list(test_list))
    # print bubbleSort2(list(test_list))
    # print selectionSort(list(test_list))
    # print insertSort(list(test_list))
    # print shellSort(list(test_list))
    mergeSort(list(test_list))
    quickSort(list(test_list))
    quickSort2(list(test_list))
#!/usr/bin/env python

import sort

a = [3, 4, 7, 8, 2, 6, 9, 1];
print sort.quickSort(a);
    file.write("%s\n" %str(vector))
    file.close()

data = []
size = int(input('Defina a quantidade de elementos da lista: '))

writeData(data, size)
start_time = timer()
print('------------------------------------\n')
print('\tQuick sort\t')
print('------------------------------------\n')
print('Antes de ordenado: ')
print(data)
print('------------------------------------\n')
print('Depois de ordenado: ')
quickSort(data, 0, size - 1)
print(data)
end_time = timer()
quicktime = (end_time - start_time)
print('------------------------------------\n')
print('Tempo = %f sec\n' % quicktime)

random.shuffle(data)

start_time = timer()
print('------------------------------------\n')
print('\tshell sort\t')
print('------------------------------------\n')
print('Antes de ordenado: ')
print(data)
print('------------------------------------\n')
Exemple #17
0
    print('2 - Scan Array')
    print('3 - Selection Sort')
    print('4 - Insertion Sort')
    print('5 - Bubble Sort')
    print('6 - Shell Sort')
    print('7 - Quick Sort')
    print('0 - Exit')
    print('==================')


def scanArray():
    for i in range(length):
        array[i] = int(input('Enter the value [' + str(i) + ']: '))
    return array


op = 1
while op:
    printMenu()
    op = int(input('Choose an option: '))

    if op == 0: print('You chose to leave')
    elif op == 1: print(array)
    elif op == 2: print(scanArray())
    elif op == 3: print(sort.selectionSort(array))
    elif op == 4: print(sort.insertionSort(array))
    elif op == 5: print(sort.bubbleSort(array))
    elif op == 6: print(sort.shellSort(array))
    elif op == 7: print(sort.quickSort(array, 0, length - 1))
    else: print('Please choose a valid option')
Exemple #18
0
    random.shuffle(data)
    res.append(copy.copy(data))

start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    insertSort(temp)
    if temp != baseData:
        print("Insertion Sort issue")
print("Insertion sort takes on average {:.5f}".format(
    (time.clock() - start) / num))

start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    quickSort(temp)
    if temp != baseData:
        print("Quick Sort issue")
print("Quick sort takes on average {:5f}".format((time.clock() - start) / num))

start = time.clock()
for i in range(num):
    temp = copy.copy(res[i])
    rquickSort(temp)
    if temp != baseData:
        print("Random Quick Sort issue")
print("Random Quick sort takes on average {:5f}".format(
    (time.clock() - start) / num))

start = time.clock()
for i in range(num):