示例#1
0
    def test_comparator(self):
        """
        Tests the comparator kwarg, which allows a user to define a 
        custom comparator function
        """
        def ascending_string_length_comparator(str_a, str_b):
            """
            @param {string} str_a
            @param {string} str_b
            @param {bool} ascending
            @return {bool} return len(str_a) > len(str_b)
            """
            # strings with less characters get moved left
            return len(str_a) > len(str_b)

        data = ['a', 'big', 'brown', 'giraffe']
        results = bubble(data, ascending_string_length_comparator)
        self.assertEqual(results[0], ['a', 'big', 'brown', 'giraffe'])
        self.assertEqual(results[1], 1)  # sweeps

        data = ['a', 'big', 'brown', 'giraffe'][::-1]  # reverse list
        results = bubble(data, ascending_string_length_comparator)
        # same results
        self.assertEqual(results[0], ['a', 'big', 'brown', 'giraffe'])
        self.assertEqual(results[1], 3)  # but more sweeps
示例#2
0
    def test_bubble(self):
        """
        Tests the bubble(list) method
        """
        data = [3, 1, 10, 9]
        results = bubble(data)
        self.assertIsInstance(results, tuple)
        self.assertEqual(results[0], [1, 3, 9, 10])
        data = random.sample(range(0, 100), 10)
        results = bubble(data)
        self.assertEqual(results[0], sorted(data))

        # test is_sorted functionality
        # sweeps should be 1 on a fully sorted list
        data = [1, 2, 3, 4, 5, 6, 7, 8, 10]
        results = bubble(data)
        self.assertEqual(results[0], [1, 2, 3, 4, 5, 6, 7, 8, 10])
        self.assertEqual(results[1], 1)  # 1 sweep

        # another more sweep, test, should be 9 sweeps
        data = [1, 2, 3, 4, 5, 6, 7, 8, 10, 0]
        results = bubble(data)
        self.assertEqual(results[0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 10])
        self.assertEqual(results[1], 9)  # 9 sweeps

        # last sweep, test, should be 2 sweeps
        data = [1, 0, 2, 3, 4, 5, 6, 7, 8, 10]
        results = bubble(data)
        self.assertEqual(results[0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 10])
        self.assertEqual(results[1], 2)  # 2 sweeps
示例#3
0
def main(args):
    numbers = get_values(args[0])
    if (len(numbers) <= 0):
        sys.exit(84)
    print(len(numbers), " element", sep="", end="")
    print("s" if len(numbers) > 1 else "")
    selection(numbers[::])
    insertion(numbers[::])
    bubble(numbers[::])
    print_res("Quicksort:", 0 if (len(numbers) <= 1) else quicksort(numbers[::])[1])
    print_res("Merge sort:", merge(numbers[::])[1])
示例#4
0
def startalgo():
    global data
    if not data: return
    timetick=speedScale.get()
    algo = algMenu.get()
    if algo == "":
        response=messagebox.showwarning("Warning","Please select the Algorithm")
    if algo == "Bubble Sort":
        bubble(data, drawData, timetick)
    if algo == "Merge Sort":
        mergesort(data,drawData,timetick)
    if algo == "Quick Sort":
        quick(data,0,len(data)-1,drawData,timetick)

    drawData(data,["#7CFC00"for x in range(len(data))])  #green
 def fill(self):
   if self.game == 'classic':
     i = 0
     for c in self:
       if self.next_line != None:
         c.append(self.next_line[i])
         i += 1
     ''' Create the next line '''
     self.next_line = list()
     for i in range(0, self.width, 1):
         self.next_line.append(bubble(True))
   else:
     for c in self:
       while len(c) < self.height:
         c.append(bubble(True))
示例#6
0
def main():
   # global variables
   global screen, pd, physenv, w, h, bubbles
   
   ## Graphics Initialization
   w, h = 400, 400
   screen = pygame.display.set_mode((w, h))
   pygame.display.set_caption("Bubble")
   pd = pygame.draw
   
   ## Setup physenv
   grav_dir_index = 0
   physenv = cake.c_master(friction=1.0, gravity_glob=[0., [0, 50, -50.][grav_dir_index]], slip=0.0)
   
   ## Bubbles
   bubble_starts = [[w/2, h/2 + [0, -100, 100][grav_dir_index]]]
   bubbles = [bubble.bubble(physenv, c, 500) for c in bubble_starts]
   bubbles[0].area *= 6

   ## Walls
   c42 = [w/2,h/2-30]
   make_wye(org = c42, channelWidth = 30, theta = n.pi/5)
   oy58 = -100
   orx58 = 50
   # physenv.make_wall([[w/2 - orx58, h/2 + oy58], [w/2 + orx58, h/2 + oy58]])

   run_continuous()
  def create_template(self, height, width):
    #Initialiser les minima et maxima
    min_x = height
    min_y = width
    max_x = 0
    max_y = 0
    color = ''
    for b in self.xbubbles:
      color = b['color']
      if min_x > b['x']:
        min_x = b['x']
      if min_y > b['y']:
        min_y = b['y']
      if max_x < b['x']:
        max_x = b['x']
      if max_y < b['y']:
        max_y = b['y']

    # Projection 
    for b in self.xbubbles:
      b['x'] -= min_x
      b['y'] -= min_y
    temp = template(False, width, height, '', 'blue')

    # Ecriture du template
    for b in self.xbubbles:
      w = bubble()
      w.color = 'blue'
      temp[b['x']][b['y']] = w
    return temp
示例#8
0
def check_sort():
    result = {
        'insert': {},
        'select': {},
        'bubble': {},
    }
    array_insert = get_array('up')
    array_select = array_insert.copy()
    array_bubble = array_insert.copy()
    result['insert']['up'] = insert(array_insert, len(array_insert))
    result['select']['up'] = select(array_select)
    result['bubble']['up'] = bubble(array_bubble)

    array_insert = get_array('down')
    array_select = array_insert.copy()
    array_bubble = array_insert.copy()
    result['insert']['down'] = insert(array_insert, len(array_insert))
    result['select']['down'] = select(array_select)
    result['bubble']['down'] = bubble(array_bubble)

    avg = {'insert': [0, 0], 'select': [0, 0], 'bubble': [0, 0]}
    for i in range(400):
        array_insert = get_array('rand')
        array_select = array_insert.copy()
        array_bubble = array_insert.copy()

        sort_result = insert(array_insert, len(array_insert))
        avg['insert'][0] += sort_result[0]
        avg['insert'][1] += sort_result[1]

        sort_result = select(array_select)
        avg['select'][0] += sort_result[0]
        avg['select'][1] += sort_result[1]

        sort_result = bubble(array_bubble)
        avg['bubble'][0] += sort_result[0]
        avg['bubble'][1] += sort_result[1]

    result['insert']['rand'] = [avg['insert'][0] / 400, avg['insert'][1] / 400]
    result['select']['rand'] = [avg['select'][0] / 400, avg['select'][1] / 400]
    result['bubble']['rand'] = [avg['bubble'][0] / 400, avg['bubble'][1] / 400]

    return result
示例#9
0
    def sortList(self):
        if self.sorted:
            return
        b = bubble()
        b.setList(self.list_to_sort)
        b.initSort()
        
        def listStep():
            if b.step():
                self.can.after(20, listStep)

        listStep()
        self.sorted = True
示例#10
0
 def __str__(self):
   '''Print the board with nice terminal colors'''
   #str = '\t'
   #str += '----------------------------------'
   #str += '\n'
   str = ''
   for j in range(self.height-1, -1, -1):
     str += '\t|  '
     for i in range(0, len(self), 1):
       if len(self[i]) <= j:
         str += bubble().__str__()
       else:
         str += self[i][j].__str__()
     str += '|\n'
   #str += '\t'
   #str += '----------------------------------'
   str += '\n'
   return str
 def __init__(self, random=False, nrow=13):
   #print 'Creation d\'une colonne avec %d lignes' % nrow
   for i in range(1, nrow, 1):
       self.append(bubble(random))
示例#12
0
print(select_arr)

count = [0, 0]
count = select.select(select_arr, dim)
print("\nУПОРЯДОЧЕННАЯ ПОСЛЕДОВАТЕЛЬНОСТЬ:")
print(select_arr)
CTotal[0] = count[0]
MTotal[0] = count[1]

count = [0, 0]
count = insert.insert(insert_arr, dim)
CTotal[1] = count[0]
MTotal[1] = count[1]

count = [0, 0]
count = bubble.bubble(bubble_arr, dim)
CTotal[2] = count[0]
MTotal[2] = count[1]
print("УПОРЯДОЧЕННАЯ ПОСЛЕДОВАТЕЛЬНОСТЬ:\n")
print("Размер массива: ", dim)
print("Сравнений:    ", CTotal[0], " ", CTotal[1], " ", CTotal[2])
print("Перестановок: ", MTotal[0], " ", MTotal[1], " ", MTotal[2])


select_arr.clear()
bubble_arr.clear()
insert_arr.clear()

for i in range(dim, 0, -1):
    select_arr.append(i)
    bubble_arr.append(i)
示例#13
0
import bubble
import insertion
import merge
import quick

looper = True  #This variable checks if you should run the program
print("Welcome to the Python Version of the Sorting Algorithms")
while looper:

    menu_choice = inputOutput.menu()  #Gets menu choice

    #Bubble Sort
    if menu_choice == "1":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Bubble Sort")
        output = bubble.bubble(data_chosen)
        inputOutput.output_list(output)

    #Insertion Sort
    elif menu_choice == "2":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Insertion Sort")
        output = insertion.insertion(data_chosen)
        inputOutput.output_list(output)

    # Merge Sort
    elif menu_choice == "3":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Merge Sort")
        output = merge.merge_sort(data_chosen)
        inputOutput.output_list(output)
def keycodedef1():
	reload(bubble)
	bubble.bubble()
	return
示例#15
0
import numpy
import sys
sys.path.insert(0, 'sorting')

nums = numpy.random.randint(100, size=20).tolist()
sortedNums = sorted(nums)

try:
    from bubble import bubble
    if (bubble(list(nums)) == sortedNums):
        print "bubblesort success!"
    else:
        print "bubblesort incorrect."
except:
    print "bubblesort function errored or is incomplete."
try:
    from insertion import insertion
    if (insertion(list(nums)) == sortedNums):
        print "insertionsort success!"
    else:
        print "insertionsort incorrect."
except:
    print "insertionsort function errored or is incomplete."
try:
    from merge import mergesort
    if (mergesort(list(nums)) == sortedNums):
        print "mergesort success!"
    else:
        print "mergesort incorrect."
except:
    print "mergesort function errored or is incomplete."
示例#16
0
#print(bucklist_detail.GetContent())

#c=upload_file_to_bucket(bucketkey,filepath,filname)

#print(c.GetContent())
## List Object in Bucket
#objectfrombucket=get_object_from_bucket('shixiangpersistent')
#print(objectfrombucket.GetContent())
## List Object in Bucket Detail
#objectfrombucket=get_object_from_bucket_detail('shixiangpersistent',filname)
#print(objectfrombucket.GetContent())

#c=POST_job(bucketkey,filname)

#print(c.GetContent())

#c=Get_urn_manifest(bucketkey,filname)
#print(c.GetContent())

#c=DELETE_urn_manifest(bucketkey,filname)
#print(c.GetContent())

#deleteobject=delete_object_from_bucket('whateverbucket','SONGYANG_6.rvt')
#print(deleteobject.GetContentObject())

#getobject=get_object_from_bucket('whateverbucket')
#print(getobject.GetContentObject().content)

b = bubble(bucketkey, filname)
ll = b.Download(r'F:\Autodesk\myforge\Tem\{filname}'.format(filname=filname))
示例#17
0
 def recycle_bubble(t):
    bubbles[0].destroy()
    center = [w/2., h/2. - 100. + 200.*t]
    bubbles[0] = bubble.bubble(physenv, center, 500)
    bubbles[0].area *= 6
示例#18
0
 def test_bubble(self):
     self.assertEqual([5, 9, 12, 24, 34], bubble([43, 12, 24, 9, 5]))
示例#19
0
 def test_8(self):
     self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8], bubble('63752841'))
示例#20
0
 def test_odd(self):
     self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], bubble('639752841'))
示例#21
0
def test_default():
    assert bubble([20, 5, 6, 3, 25, 15]) == [3, 5, 6, 15, 20, 25]
示例#22
0
 def test_repeat(self):
     self.assertEqual([1, 1, 1, 1], bubble('1111'))
示例#23
0
import numpy

from bubble import bubble

numbers = numpy.random.randint(0, 100, numpy.random.randint(10, 50))
print(numbers)
print(bubble(numbers))
示例#24
0
 def test_2(self):
     self.assertEqual([1, 2], bubble('21'))
def keycodedef0():
	bubble.bubble()
	return
示例#26
0
    # merge ######################################################################################
    t1 = time.time()
    usu = v.copy()
    usu = merge.merge(usu)
    for i in usu:
        g.write(str(i) + ' ')
    g.write('\n')
    t2 = time.time()
    g.write("Merge a durat: " + str(t2 - t1) + '\n')
    ##############################################################################################

    # bubble #####################################################################################
    t1 = time.time()
    usu = v.copy()
    usu = bubble.bubble(usu)
    t2 = time.time()
    if (usu[0] == -10e100):
        g.write("Bubble a durat peste 5 secunda; am intrerupt sortarea\n")
    else:
        g.write("Bubble a durat: " + str(t2 - t1) + '\n')
    ##############################################################################################

    # count ######################################################################################
    t1 = time.time()
    usu = v.copy()
    usu = count.count(usu)
    t2 = time.time()
    g.write("Count a durat: " + str(t2 - t1) + '\n')
    ##############################################################################################
    import random

    before = random.sample(range(1, 1000000), 10000)

    return before


if __name__ == '__main__':
    import time

    before = unsorted()
    print(before)

    # bubble
    start_b = time.time()
    sorted_bubble = bubble.bubble(before)
    print(sorted_bubble)
    end_b = time.time()
    print('bubble', end_b - start_b)

    # selection
    start_s = time.time()
    sorted_selection = selection.selection(before)
    print(sorted_selection)
    end_s = time.time()
    print('selection', end_s - start_s)

    # insertion
    start_i = time.time()
    sorted_insertion = insertion.insertion(before)
    print(sorted_insertion)
示例#28
0
#print(bucklist.GetContentObject().content)

filepath = r'E:\01_TenElephant_Project\2018_Project\20880414 SongYang_Project\02 BIM_单体\#1\20180419 中心文件\SONGYANG_1_code_fin.rvt'
filename = r'SONGYANG_1_fin.rvt'

#c=upload_file_to_bucket('shixiang',filepath,filename)

#print(c.GetContentObject().content)
#c=POST_job('shixiang',filename)

#print(c.GetContentObject().content)

#c=Get_urn_manifest("shixiang",filename)
#print(c.GetContentObject().content)

#c=DELETE_urn_manifest("shixiang",filename)
#print(c.GetContentObject().content)

#objectfrombucket=get_object_from_bucket('shixiang')
#print(objectfrombucket.GetContentAsJson())

#deleteobject=delete_object_from_bucket('shixiang',filename)
#print(deleteobject.GetContentObject().content)

b = bubble('shixiang', filename)
ll = b.Download(r'C:\Users\2016028\Desktop\Tem\SongYang__All\Tem1')

#c=authenticate.authenticate()

#print(c.get_access_token)