Esempio n. 1
0
def bubble_sort(boxes):
    initial_color = "#2299AB"
    comparision_color = "#8D00FF"
    final_color = "#00FFCE"
    animation_speed = 1

    # Set all boxes color to initial color
    for box in boxes:
        set_color(box, initial_color, canvas)

    n = len(boxes)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if boxes[j] > boxes[j + 1]:
                set_color(boxes[j], comparision_color, canvas)
                set_color(boxes[j + 1], comparision_color, canvas)

                swap(boxes[j], boxes[j + 1], animation_speed, canvas, tk)
                boxes[j], boxes[j + 1] = boxes[j + 1], boxes[j]

                time.sleep(0.1)

                set_color(boxes[j], initial_color, canvas)
                set_color(boxes[j + 1], initial_color, canvas)

        set_color(boxes[j + 1], final_color, canvas)

    set_color(boxes[0], final_color, canvas)
Esempio n. 2
0
 def _bubble_up(self, i):
     parent_idx = self._get_parent_index(i)
     while parent_idx is not None:
         if self.heap[i] < self.heap[parent_idx]:
             swap(self.heap, i, parent_idx)
         i = parent_idx
         parent_idx = self._get_parent_index(parent_idx)
Esempio n. 3
0
 def evolve(self, init, max_gen, k_opt=2):
     x = init
     gen = 0
     tabu_list = [0] * self.tabu_size
     while gen < max_gen:
         print('gen %d...' % gen, end='')
         x_neighbors, rules = get_neighbors_and_rules(x, k_opt) # 2-opt is usually better
         dists = list(map(lambda x : distance(self.distance_matrix, x), x_neighbors))
         sorted_dists, sorted_index = sort(dists)
         min_dist = sorted_dists[0]
         min_id = sorted_index[0]
         min_rule = rules[min_id]
         if min_dist < distance(self.distance_matrix, x): # aspiration
             # update tabu list
             tabu_list.insert(0, min_rule)
             tabu_list.pop()
             x = swap(x, min_rule)
         else:
             while min_rule in tabu_list:
                 sorted_index.pop(0)
                 min_id = sorted_index[0]
                 min_rule = rules[min_id]
             # update tabu list
             tabu_list.insert(0, min_rule)
             tabu_list.pop()
             x = swap(x, min_rule)
         gen += 1
         print('done!')
     return tabu_list, x, distance(self.distance_matrix, x)
Esempio n. 4
0
def credential_manager():
    os.system('find -name encrypted.txt | cut -b 3- >> hasname.txt')
    if utils.swap('hasname.txt', True).pop() == 'encrypted.txt':
        uname = 'pi'
        os.system('echo $(python aes.py -d) >> passd.txt')
        passwd = utils.swap('passd.txt', True).pop().split('Result: ')[1]
    return uname, passwd
Esempio n. 5
0
def greedyLocalSearch(distances, type):
    number_of_all = distances.shape[0]
    number_of_half = int(np.ceil(number_of_all / 2))
    path, not_path = utils.make_random_path(number_of_half, number_of_all)
    actions = utils.swap_actions(number_of_half, type)
    result_of_itertools_product = itertools.product(
        np.arange(path.shape[0]), np.arange(not_path.shape[0]))
    exchange_actions = np.array(list(result_of_itertools_product), 'int')
    swapLen, exchangeLen = len(actions), len(exchange_actions)
    swapWithNoImprovement, exchangeWithNoImprovement = 0, 0
    np.random.shuffle(exchange_actions)
    np.random.shuffle(actions)

    while True:
        if swapLen <= swapWithNoImprovement and exchangeLen <= exchangeWithNoImprovement:
            break
        elif np.random.random() < 0.5 and swapLen > swapWithNoImprovement:
            action = actions[np.random.randint(len(actions)), :]
            delta = utils.calculate_swap_delta(action, path, distances, type)
            if delta > 0:
                utils.swap(path, action, type)
                swapWithNoImprovement = 0
            else:
                swapWithNoImprovement += 1
        else:
            exchange_action = actions[np.random.randint(len(actions)), :]
            delta = utils.calculate_exchange_delta(exchange_action, path,
                                                   not_path, distances)
            if delta > 0:
                utils.exchange_vertices(path, not_path, exchange_action)
                exchangeWithNoImprovement = 0
            else:
                exchangeWithNoImprovement += 1
    return np.append(path, path[0])
Esempio n. 6
0
def insertion_sort(a):
    i = 0
    while i < len(a) - 1:
        j = i + 1
        while j > 0 and a[j] < a[j - 1]:
            swap(a, j - 1, j)
            j -= 1
        i += 1
Esempio n. 7
0
def insertion_sort(arr):
    for n in xrange(1, len(arr)):
        for m in xrange(n, 0, -1):
            if arr[m] < arr[m - 1]:
                utils.swap(arr, m, m - 1)
            else:
                break
    return arr
Esempio n. 8
0
def selection_sort(a):
    for i in range(len(a)):
        min_index = i
        for j in range(i + 1, len(a)):
            if a[j] < a[min_index]:
                min_index = j

        if min_index != i:
            swap(a, min_index, i)
Esempio n. 9
0
def selection_sort(arr):
    for x in xrange(0, len(arr)):
        mini = x
        for y in xrange(x, len(arr)):
            if arr[y] < arr[mini]:
                mini = y
        swap(arr, x, mini)

    return arr
Esempio n. 10
0
def sort(A):
    heap_size = len(A)

    build_max_heap(A)

    for i in range(len(A) - 1, 0, -1):
        swap(A, 0, i)
        heap_size -= 1

        max_heapify(A, 0, heap_size)
Esempio n. 11
0
def bubble_sort(arr):
    in_order = False
    while not in_order:
        in_order = True
        for x in xrange(0, len(arr) - 1):
            if arr[x] > arr[x + 1]:
                swap(arr, x, x + 1)
                in_order = False

    return arr
def bubble(collection):
	n = len(collection)
	for i in range(0, n - 1):
		no_change = True
		for j in range(0, n - i - 1):
			if collection[j + 1] < collection[j]:
				swap(collection, j, j + 1)
				no_change = False
		if no_change:
			return
Esempio n. 13
0
def SWAP3(tau, LTG, LTG1, LTG2, C, Q, EG, V, SPL, QFilter_type):
    QFilter = Q_Filter(tau, LTG, LTG1, C, Q, EG)
    if QFilter_type == '9':  #no filter is used
        QF1, QF2, QF3 = QFilter[0], QFilter[0], QFilter[0]
    elif QFilter_type == '0':  #only Q1-filter (note in the paper this is called Q0-filter)
        QF1, QF2, QF3 = QFilter[1], QFilter[1], QFilter[1]
    elif QFilter_type == '01':  #Q1-filter for the first layer and Q2-filter for the rest (Q0+Q1-filter in the paper)
        QF1, QF2, QF3 = QFilter[1], QFilter[2], QFilter[2]
    elif QFilter_type == '01x':  #Q1-filter for the first layer and (Q1+Q2)-filter for the rest (Q0+weak_Q1-filter
        QF1, QF2, QF3 = QFilter[1], QFilter[3], QFilter[3]
    elif QFilter_type == '1x':  #only Q2x-filter
        QF1, QF2, QF3 = QFilter[3], QFilter[3], QFilter[3]
    else:  #'01y'
        QF1, QF2, QF3 = QFilter[3], QFilter[1], QFilter[1]

    SWAP3 = []
    rhat = R_hat_3(tau, LTG, LTG1, LTG2, C, V, SPL)
    for edge_1 in EG:
        p, q = edge_1
        if tau[p] not in QF1 and tau[q] not in QF1: continue
        tau1 = swap(tau, p, q, EG)
        rhat1 = R_hat_3(tau1, LTG, LTG1, LTG2, C, V, SPL)
        if rhat1 > rhat: continue
        x1 = [[edge_1], tau1]
        if x1 not in SWAP3:
            SWAP3.append(x1)

        for edge_2 in EG:
            if edge_1 == edge_2: continue
            p, q = edge_2
            if tau1[p] not in QF2 and tau1[q] not in QF2:
                continue
            tau2 = swap(tau1, p, q, EG)
            rhat2 = R_hat_3(tau2, LTG, LTG1, LTG2, C, V, SPL)
            if rhat2 > rhat1: continue
            x2 = [[edge_1, edge_2], tau2]
            if x2 not in SWAP3:
                SWAP3.append(x2)

            for edge_3 in EG:
                if edge_3 in {edge_1, edge_2}: continue
                p, q = edge_3
                if tau2[p] not in QF3 and tau2[q] not in QF3: continue
                tau3 = swap(tau2, p, q, EG)
                mdg3 = min_gate_dist(tau3, LTG, C, V, SPL)
                if mdg3 > 1: continue
                '''//Compare with the above, i.e., mdg3'''
                #2.6155@729"(rhat3) vs 2.6179@746(mdg3) vs 2.6155@789" (sycamore)
                #3.1494@466"(rhat3) vs.3.1415@441"(mdg3) vs 3.1494@438" (rochester)
                # rhat3 = R_hat_3(tau3, LTG, LTG1, LTG2, C, V, SPL)
                # if rhat3 > rhat2: continue
                x3 = [[edge_1, edge_2, edge_3], tau3]
                if x3 not in SWAP3:
                    SWAP3.append(x3)
    return SWAP3
Esempio n. 14
0
def partition(A, lo, hi):
    p = select_pivot(A, lo, hi)
    i = lo + 1

    for j in xrange(i, hi + 1):
        if A[j] < A[p]:
            swap(A, i, j)
            i += 1

    swap(A, i-1, p)
    return i-1
Esempio n. 15
0
def partition(arr, l, r):
    pivot = l
    i = pivot + 1
    j = i
    while i < r:
        if arr[i] < arr[pivot]:
            swap(arr, i, j)
            j += 1
        i += 1
    swap(arr, pivot, j-1)
    return j-1
Esempio n. 16
0
def heapsort(A: list):
    n = len(A)
    mid = n // 2 - 1

    for l in range(mid, -1, -1):
        sift(A, l, n - 1)

    for r in (n - 1, 1, -1):
        swap(A, pos1=0, pos2=r)
        sift(A, 1, r)
    A.reverse()
Esempio n. 17
0
    def insert_second(self, data):
        n = len(self._list)
        self._list.append(data)

        i = first_size
        while i > 0:
            swap(self._list, n - 1, n)
            n -= 1
            i -= 1

        second_size += 1
def bubbleSort(A):
    n_swap, n_compare = 0, 0
    for i in range(len(A) - 1):
        for j in range(i, len(A) - 1):
            n_compare += 1
            if A[j] > A[j + 1]:
                swap(A, j, j + 1)
                n_swap += 1
    benchmarks = {'n_compare': n_compare, 'n_swap': n_swap}
    return A, benchmarks

    return A
Esempio n. 19
0
def partition(arr, low, high):
    pivotIndex = low
    low = low + 1

    for x in xrange(low, high + 1):
        if arr[x] < arr[pivotIndex]:
            swap(arr, x, low)
            low = low + 1

    swap(arr, pivotIndex, low - 1)

    return low - 1
Esempio n. 20
0
 def initialize(self):
     os.system('ls KB/ >> topics.txt')
     known_subjects = utils.swap('topics.txt', True)
     for subj in known_subjects:
         topic = subj.split('_result.txt')[0].replace('_', "")
         self.kb[topic] = utils.swap('KB/' + subj, False)
         sz = len(self.kb[topic])
         print 'Importing Knowledge of subject\t%s\033[1m\t\b%d lines\033[0m' % (
             topic, sz)
     vocabulary = utils.swap('words.txt', False)
     print '\033[1m\033[34m%d Words Added to Vocabulary\033[0m' % (
         len(vocabulary))
Esempio n. 21
0
        def insert_kp(arr, kp, idx):
            if len(arr) < num_per_blk:
                arr.append(idx)
            elif kps_all[arr[-1]].response < kp.response:
                arr[-1] = idx
            else:
                return

            for kk in range(-1, -len(arr), -1):
                if kps_all[arr[kk - 1]].response >= kp.response:
                    break
                swap(arr, kk, kk - 1)
Esempio n. 22
0
def SWAP3(tau, LTG, LTG1, C, Q, EG, V, SPL, QFilter_type):
    QFilter = Q_Filter(tau, LTG, LTG1, C, Q, EG)
    if QFilter_type == '9':  #no filter is used
        QF1, QF2, QF3 = QFilter[0], QFilter[0], QFilter[0]
    elif QFilter_type == '0':  #only Q1-filter (note in the paper this is called Q0-filter)
        QF1, QF2, QF3 = QFilter[1], QFilter[1], QFilter[1]
    elif QFilter_type == '01':  #Q1-filter for the first layer and Q2-filter for the rest (Q0+Q1-filter in the paper)
        QF1, QF2, QF3 = QFilter[1], QFilter[2], QFilter[2]
    elif QFilter_type == '01x':  #Q1-filter for the first layer and (Q1+Q2)-filter for the rest (Q0+weak_Q1-filter
        QF1, QF2, QF3 = QFilter[1], QFilter[3], QFilter[3]
    elif QFilter_type == '1x':  #only Q2x-filter
        QF1, QF2, QF3 = QFilter[3], QFilter[3], QFilter[3]
    else:  #'01y'
        QF1, QF2, QF3 = QFilter[3], QFilter[1], QFilter[1]

    SWAP3 = []
    rhat = R_hat_1(tau, LTG, C, V, SPL)
    for edge_1 in EG:
        p, q = edge_1
        #skip if both p, q are irrelevant phy. qubits w.r.t. TG
        if tau[p] not in QF1 and tau[q] not in QF1: continue
        tau1 = swap(tau, p, q, EG)
        rhat1 = R_hat_1(tau1, LTG, C, V, SPL)
        if rhat1 > rhat: continue
        x1 = [[edge_1], tau1]
        if x1 not in SWAP3:
            SWAP3.append(x1)

        for edge_2 in EG:
            if edge_1 == edge_2: continue
            p, q = edge_2
            if tau1[p] not in QF2 and tau1[q] not in QF2: continue
            tau2 = swap(tau1, p, q, EG)
            rhat2 = R_hat_1(tau2, LTG, C, V, SPL)
            if rhat2 > rhat1: continue
            x2 = [[edge_1, edge_2], tau2]
            if x2 not in SWAP3:
                SWAP3.append(x2)

            for edge_3 in EG:
                if edge_3 in {edge_1, edge_2}: continue
                p, q = edge_3
                if tau2[p] not in QF3 and tau2[q] not in QF3: continue

                tau3 = swap(tau2, p, q, EG)
                mdg3 = min_gate_dist(tau3, LTG, C, V, SPL)
                '''If GVal, we aim to solve at least one gate.'''
                if mdg3 > 1: continue
                x3 = [[edge_1, edge_2, edge_3], tau3]
                if x3 not in SWAP3:
                    SWAP3.append(x3)
    return SWAP3
Esempio n. 23
0
def selectionSort(A):
    n_compare, n_swap = 0, 0

    for i in range(len(A)):
        least_ix = len(A) - 1
        for j in range(i, len(A)):
            n_compare += 1
            if A[j] < A[least_ix]:
                least_ix = j
        swap(A, i, least_ix)
        n_swap += 1
    benchmarks = {'n_compare': n_compare, 'n_swap': n_swap}
    return A, benchmarks
Esempio n. 24
0
def selectionSort(lyst):
    i = 0
    while i < len(lyst) - 1:
        minIndex = i
        j = i + 1
        while j < len(lyst):
            if lyst[j] < lyst[minIndex]:
                minIndex = j
            j += 1
        if minIndex != i:
            swap(lyst, minIndex, i)
        i += 1
        time.sleep(0.1)
    return lyst
Esempio n. 25
0
def max_heapify(A, i, heap_size):
    l = (i << 1) + 1
    r = l + 1
    largest = i

    if l < heap_size and A[l] > A[i]:
        largest = l

    if r < heap_size and A[r] > A[largest]:
        largest = r

    if largest != i:
        swap(A, i, largest)

        max_heapify(A, largest, heap_size)
Esempio n. 26
0
    def bfs(self, u):
        visited = [False] * (len(self.__edges))
        tree = []
        queue = [u]
        visited[u] = True
        while queue:
            s = queue.pop(0)
            print(f"{s}", end=" ")
            for e in self.__edges[s]:
                if visited[e] is False:
                    visited[e] = True
                    queue.append(e)
                    tree.append([e, s])

        utils.swap(tree)
        print(f"\n{tree}")
Esempio n. 27
0
 def load_training_data():
     raw_data_in = []
     for table_data in utils.swap('unlabeled_training_data.txt', False):
         raw_data_in.append(table_data)
     print '[*] %d lines of unlabeled training data loaded [%ss Elapsed]' % \
           (len(raw_data_in), str(time.time() - tic))
     return raw_data_in
def solve_n_queens_problem(number_of_queens, population_size=10**3, max_iterations=10**4):
    assert 0 < number_of_queens < 256
    indices = numpy.arange(number_of_queens)

    # def swap_2_random_rows(population, all_rows=indices):
    #     perm, rand_rows = sample(population, 1)[0], sample(all_rows, 2)
    #     new_perm = perm.copy()
    #     new_perm[rand_rows[::-1]] = perm[rand_rows[0]], perm[rand_rows[1]]
    #     return new_perm
    swap_2_random_rows = lambda population, all_rows=indices: swap(sample(population, 1)[0], sample(all_rows, 2))

    numb_of_parents = 2
    chromo_length = number_of_queens/numb_of_parents
    slices = tuple(imap(
        apply,
        repeat(slice),
        izip_longest(*imap(xrange, (0, chromo_length), repeat(number_of_queens - 1), repeat(chromo_length))),
    ))

    def merge_2_random_solutions(population):
        return permutation_from_inversion(  # merge two solutions by merging their inversion sequence ...
            numpy.fromiter(
                chain.from_iterable(
                    imap(  # get inversion sequence from each donor parent ...
                        item,
                        imap(tuple, imap(permutation_inversion, sample(population, numb_of_parents))),
                        slices
                    )
                ),
                count=number_of_queens,
                dtype=board_element_type
            )
        )

    operators = merge_2_random_solutions, swap_2_random_rows

    def genetic_operators(population, sample_size, prob_of_mutation=.3):
        return sorted(
            imap(apply, imap(operators.__getitem__, random(sample_size) < prob_of_mutation), repeat((population,))),
            key=fitness_function,
            reverse=True
        )

    return genetic_algorithm(
        sorted(
            starmap(
                sample,
                repeat((numpy.arange(number_of_queens, dtype=board_element_type), number_of_queens), population_size)
            ),
            key=fitness_function,
            reverse=True
        ),
        selection,
        genetic_operators,
        sort_population,
        lambda perm: len(perm) - fitness_function(perm),
        max_iterations=max_iterations
    )
Esempio n. 29
0
def main():
    if '-gen' in sys.argv:
        A = int(sys.argv[2])
        B = int(sys.argv[3])
        ip_block(A, B)

    # Create a way to run this distributed from python
    elif '-multi-setup' in sys.argv:
        import network
        workers = []
        peers = {}
        # Determine which nodes are available to work
        for n in network.get_node_names():
            name = n.split('/')[-1].split('.')[0]
            h, i, p, m = utils.load_credentials(name, False)
            peers[name] = [h, i, p, m]
            # check if online
            if network.check_connected(h, i, p):
                workers.append(name)
            else:
                print '%s@%s offline' % (name, i)

        # Now distribute the assignments
        print '[*] %d Workers Available' % len(workers)
        for w in workers:
            # give them the latest copy of this program
            H, I, P, M = peers[w]
            rpath = '/home/%s/Documents/PoolParty/code/0.6/' % H
            if utils.remote_file_exists(H, I, P, rpath + 'trace.py'):
                utils.ssh_exec('rm %strace.py' % rpath, I, H, P, False)
            utils.put_file('trace.py', rpath, H, I, P, False)
            # Now give them a ip_space.txt file and a script to run trace.py
            utils.ssh_exec('rm %shops.txt' % rpath, I, H, P, True)
            # c = 'cd %s; python trace.py 0>&-' % rpath
            # put this in a .sh script and transfer, then execute
            # utils.ssh_exec('cd %s; python trace.py 0>&-' % rpath,H,I,P,False)

    elif '-multi-view' in sys.argv:
        import tracewatch
        print('[*] Monitoring Traces...')

    else:
        ips = list(utils.swap('ip_space.txt', False))
        if not os.path.isfile(os.getcwd() + '/hops.txt'):
            os.system('touch hops.txt')
        random.shuffle(ips)
        pool = multiprocessing.Pool(10)
        for ip in ips:
            try:
                event = pool.apply_async(func=trace, args=(ip, False))
                hopdata, nhops = event.get(timeout=60)
                print ' - %d hops to %s' % (nhops, ip)
                open('hops.txt', 'a').write('%s:%d\n' % (ip, nhops))
            except multiprocessing.TimeoutError:
                open('hops.txt', 'a').write('%s:?\n' % ip)
                pass
Esempio n. 30
0
 def double_gate(self, T, i, j=None):
     """Apply the double-qubit transformation T to the ith and jth qubits,
     or ith and i+1th if j is not specified
     
     >>> qs = QSystem(3)
     >>> qs.single_gate(H, 0)
     >>> qs.double_gate(CNOT, 0)
     >>> qs
     (0.707106781187+0j)|000> + 0j|001> + 0j|010> + 0j|011> + 0j|100> + 0j|101> + (0.707106781187+0j)|110> + 0j|111>
     >>> qs = QSystem(3)
     >>> qs.single_gate(H, 0)
     >>> qs.double_gate(CNOT, 0, 2)
     >>> qs
     (0.707106781187+0j)|000> + 0j|001> + 0j|010> + 0j|011> + 0j|100> + (0.707106781187+0j)|101> + 0j|110> + 0j|111>
     """
     if i < 0 or i >= self.N - 1:
         raise ValueError("Invalid qubit: " + str(i))
     # self.N - 1 transformations because T acts on 2 qubits
     transforms = [I] * (self.N - 1)
     transforms[i] = T
     # Switch the order of the qubits so i and j are adjacent
     # i.g. i = 0, j = 2
     #            ___
     # 0 ________|   |_______
     #           | T |
     # 1 ___  ___|   |__  ___
     #      \/   |___|  \/
     # 2 ___/\__________/\___
     if j:
         S = utils.swap(self.N, i + 1, j)
         self._state = S.dot(self._state)
     e = None
     try:
         self.transform(transforms)
     except ValueError as v:
         e = v
     # Switch back
     if j:
         S = utils.swap(self.N, i + 1, j)
         self._state = S.dot(self._state)
     if e:
         # make sure the system is switched back if there is an error
         raise e
Esempio n. 31
0
def process_hops():
    maximum = 0
    n_traces = 0
    for line in utils.swap('hops.txt', True):
        hstr = line.replace('\n', '').split(':')[1]
        if hstr != '?':
            hops = int(line.replace('\n', '').split(':')[1])
            if hops > maximum:
                maximum = hops
        n_traces += 1
    return maximum, n_traces
Esempio n. 32
0
def partition(a, start, end):
    pivot = start
    left = start + 1
    right = end
   
    done = False
    while not done:
        while left <= right and a[left] <= a[pivot]:
            left += 1

        while left <= right and a[right] >= a[pivot]:
            right -= 1

        if right < left:
            done = True
        else:
            swap(a, left, right)
    
    swap(a, pivot, right)
    return right
Esempio n. 33
0
def parse_scan(filename):
    scan = {}
    ports = []
    for line in utils.swap(filename, False):
        try:
            scan['ip'] = line.split(' scan report for ')[1].split(' ')[0]
        except IndexError:
            pass
        try:  # Including Filtered as well
            if ('open' or 'filtered') in line.split(' '):
                ports.append(line.split(' open ')[1].replace(' ', ''))
        except IndexError:
            pass
    scan['open'] = ports
    return scan
 def permutation_function(current_solution, row_indices=numpy.arange(number_of_queens)):
     return swap(current_solution, sample(row_indices, 2))   # swap two random rows.