def answer3(a): #使用快慢指针来均分链表, 然后把后面一半倒序, 拆分为2个队列,上看去更简洁
    slow = fast = a.first
    pre = None
    while fast:
        pre = slow
        slow = slow.next
        if fast.next:
            fast = fast.next.next
        else:
            fast = fast.next
        if fast == a.last:
            break;
    pre.next = None
    a.last = pre
    
    b = Queue()
    while slow:
        b.add(slow)
        slow = slow.next
    import reverse_list
    b2 = reverse_list.answer(b)
    
    r = Queue()
    while a.element() and b.element() :
        r.add(Node(a.remove().value))
        r.add(Node(b.remove().value))
    if b.element():
        r.add(Node(b.remove().value))
      
    return r
Example #2
0
def test_filled_queue():
    queue = Queue()
    queue.add(1)
    assert queue.remove() == 1
    queue.add(1).add(2).add(3)
    assert queue.remove() == 1
    assert queue.remove() == 2
Example #3
0
 def test_remove(self):
     queue = Queue()
     queue.add(1)
     self.assertEqual(1, queue.remove())
     self.assertTrue(queue.isEmpty())
     queue.add(2)
     queue.add(3)
     self.assertEqual(2, queue.remove())
     self.assertEqual(3, queue.remove())
     self.assertTrue(queue.isEmpty())
def spin(alist, marker):

    circle = Queue()

    for student in alist:
        circle.add(student)

    while len(circle) > 1:

        for round in range(marker):
            circle.add(circle.remove())

        circle.remove()

    return circle[0]
Example #5
0
def find_path(node_a, node_b):
    if node_a == node_b:
        return True

    queue = Queue()
    queue.add(node_a)
    node_a.visited = True

    while not queue.is_empty():
        children = queue.remove()

        if children:
            for child in children:
                if child.visited == False:
                    child.visited = True

                    if child == node_b:
                        return True

                    queue.add(child)

            children.visited = True


    return False
Example #6
0
def main():
    employee_directory = []
    sudo_usernames_data = [
        "Inger Hella", "Saga Janina", "Alfred Dorotea", "Tessan Helen",
        "Michael Rigmor", "Edith Ida", "John Henrike", "Hella Lukas",
        "Thyra Karolina", "Øyvind Nathalie", "Miroslav Tikhon",
        "Tòmas Prokhor", "Timofei Vitaliy", "Beileag Logan", "Filipp Vadim",
        "Ruaridh Lilia", "Filat Svyatoslav", "Sofiya Bhaltair", "Max Saveli",
        "Yeva Snezhana"
    ]

    for i, val in enumerate(sudo_usernames_data):
        # output = f'{i} {val} {random.randrange(100,999)} {predict_shift[random.randrange(1,4)]}'
        employee_directory.append(
            Employee(val, random.randrange(100, 999), random.randrange(1, 4)))
        # print(employee_directory[i].to_string())
    print("Before id number sort: \n ----------")
    EmployeeArrayUtilities.print_array(employee_directory)

    array_size = len(employee_directory)
    EmployeeArrayUtilities.print_array(employee_directory,
                                       "\nBefore last-name sort:")
    EmployeeArrayUtilities.sort_array(employee_directory, array_size)
    EmployeeArrayUtilities.print_array(employee_directory,
                                       "\nAfter last-name sort: ")

    s1 = Queue(10, Employee())

    print("Enter an employee number to add to the queue: ", end="")
    new_search_value = input()
    # s1 = Queue(10, 0)

    found = EmployeeArrayUtilities.binary_search_number(
        employee_directory, int(new_search_value), 0, array_size - 1)
    # print("found: ", found)
    if found != EmployeeArrayUtilities.NOT_FOUND:
        print(new_search_value + " IS in list at position " + str(found))
    else:
        print(new_search_value + " is NOT in list.")
    # print("capacity: ", s1.get_capacity())
    # print(employee_directory[0])
    # s1.add(employee_directory[0])
    # s1.add(employee_directory[1])
    # s1.add(employee_directory[2])
    # s1.add(employee_directory[3])
    # s1.add(employee_directory[4])

    s1.add(1)
    s1.add(2)
    s1.add(3)
    s1.add(4)
    s1.add(5)
    s1.add(6)

    print(s1.que)

    for k in range(0, 3):
        print("[" + str(s1.remove()) + "]")

    print(s1.que)
Example #7
0
    def __repr__(self):
        """String representation."""
        queue = Queue()
        self.marked = True
        queue.add(self)
        s = ''
        counter = 1
        depth = 0

        while not queue.is_empty():
            r = queue.remove()
            s += str(r.name)
            s += '\t'

            if counter == 2**depth:
                s += '\n'
                counter = 0
                depth += 1

            counter += 1

            if r.left is not None:
                if r.left.marked == False:
                    r.left.marked = True
                    queue.add(r.left)
            if r.right is not None:
                if r.right.marked == False:
                    r.right.marked = True
                    queue.add(r.right)
        return s
Example #8
0
class Character:
    def __init__(self, move_list, speed):
        self.move_list = move_list
        self.speed = speed
        self.move_queue = Queue()

    def queue_move(self, move):
        self.move_queue.add(move)

    def perform_move(self):
        move = self.move_queue.remove()

    def start(self):
        while (self.move_queue.empty() == False):
            seconds = floor((20 / self.speed))
            time.sleep(seconds)
            action = self.move_queue.remove()
            print('Performing Action:', action)
Example #9
0
def test_queue(N):
    print("Testing queue")
    q = Queue()

    print("Check if empty")
    print(q.empty())

    print(f"Adding {N} values")
    [q.add(i) for i in range(N)]

    print("")
    print("Peeking front value")
    print(q.peek())
    print("Removing values")
    [q.remove() for i in range(int(N / 2) - 1)]
    print("Mid-value:")
    print(q.remove())
    [q.remove() for i in range(int(N / 2))]
    print("Queue should now be empty")
    try:
        q.remove()
    except Exception:
        print("Got expected Exception")
Example #10
0
class AnimalShelter:
    def __init__(self):
        self.cats = Queue()
        self.dogs = Queue()
        self.pos = 0

    # Time complexity: O(1)
    # Space complexity: O(1)
    def enqueue(self, animal: Animal):
        if animal == Animal.cat:
            self.cats.add([animal, self.pos])
        else:
            self.dogs.add([animal, self.pos])

        self.pos += 1

        return self

    # Time complexity: O(1)
    # Space complexity: O(1)
    def dequeue(self):
        if self.dogs.is_empty() and self.cats.is_empty():
            raise Exception('no animal in shelter')

        if self.dogs.is_empty():
            return self.cats.remove()

        if self.cats.is_empty():
            return self.dogs.remove()

        dog_pos = self.dogs.peek()[1]
        cat_pos = self.cats.peek()[1]

        if cat_pos < dog_pos:
            return self.cats.remove()
        else:
            return self.dogs.remove()

    # Time complexity: O(1)
    # Space complexity: O(1)
    def dequeueCat(self):
        if self.cats.is_empty():
            raise Exception('no cats in shelter')

        return self.cats.remove()

    # Time complexity: O(1)
    # Space complexity: O(1)
    def dequeueDog(self):
        if self.dogs.is_empty():
            raise Exception('no dogs in shelter')

        return self.dogs.remove()

    def __str__(self):
        return 'cats: ' + str(self.cats) + '\ndogs: ' + str(self.dogs)
def breadth_first_search(value, root):
    """Using a Queue"""
    queue = Queue()
    queue.add(root)

    while queue.queue:
        node = queue.remove()
        print(node)
        if node.data == value:
            return True
        else:
            for child in node.children:
                queue.add(child)

    return False
Example #12
0
    def __str__(self):
        queue = Queue()
        queue.add(self.root)
        values = []

        while not queue.is_empty():
            exp = queue.remove()
            values.append(str(exp.value))

            if exp.value.left:
                queue.add(exp.value.left)
            if exp.value.right:
                queue.add(exp.value.right)

        return str(values)
Example #13
0
def BFS(node):
	queue=Queue()
	queue.add(node)
	visited=set()
	visited.add(node)
	
	while not queue.is_empty():
		r=queue.remove()
		print(r.value)
		
		if r.left!=None:
			if r.left not in visited:
				queue.add(r.left)
				visited.add(r.left)
		if r.right!=None:
			if r.right not in visited:
				queue.add(r.right)
				visited.add(r.right)
Example #14
0
def breadth_first_search(value, root):
    """Using a Queue"""
    queue = Queue()
    queue.add(root)

    while queue.queue:
        node = queue.remove()
        print(node)
        if node.data == value:
            return True
        else:
            if node.left:
                queue.add(node.left)

            if node.right:
                queue.add(node.right)

    return False
def BFS(start, end):
    queue = Queue()
    queue.add(start)

    visited_set = {}
    visited_set[start.label] = True

    while not queue.is_empty():
        current = queue.remove()
        for i in range(current.neighbors_num):
            node = current.neighbors[i]
            if not visited_set.has_key(node.label):
                visited_set[node.label] = True
                if node.label == end.label:
                    return True
                else:
                    queue.add(node)
    return False
Example #16
0
def list_of_depths(bt: BinarySearchTree):
    nodes = {}
    que = Queue()
    que.add([bt.root, 1])

    while not que.is_empty():
        (node, pos) = que.remove().value

        if not nodes.get(pos):
            nodes[pos] = LinkedList()

        nodes[pos].unshift(node.value)

        if node.left:
            que.add([node.left, pos + 1])
        if node.right:
            que.add([node.right, pos + 1])

    return nodes
Example #17
0
class QueueSimulation:
    def __init__(self, process_rate, min, max, capacity):
        self.process_rate = process_rate
        self.min_req_rate = min
        self.max_req_rate = max
        self.capacity = capacity
        self.queue = Queue(self.capacity)

    def step(self, requests):
        self.requests = requests
        results, lost_count = [], 0
        while self.queue.is_empty() == False:
            results.append(self.queue.remove())

        l = len(results)
        for i in range(len(self.requests)):
            if i < self.process_rate - l:
                results.append(self.requests[i])
            elif i >= self.process_rate - l and i < self.process_rate - l + self.capacity:
                self.queue.insert(self.requests[i])
            else:
                lost_count += 1
        return results, lost_count

    def run(self, times):
        self.times = times
        lost_requests = []
        du = 0
        for i in range(times):
            req_rate = random.randint(self.min_req_rate, self.max_req_rate)
            if du + req_rate <= self.process_rate:
                lost_requests.append(0)
            else:
                du = req_rate - self.process_rate + du
                if du > self.capacity:
                    lost_requests.append(du - self.capacity)
                    du = self.capacity
                else:
                    lost_requests.append(0)
        tong = 0
        for l in lost_requests:
            tong += l
        return tong / times
Example #18
0
def BFS(maze, start, goal):
    maze = copy.deepcopy(maze)  # Create a copy so we can modify it
    q = Queue()  # Queue for traversing breadth-first
    start = (start[0], start[1], None)  # Change to mode with parent
    q.insert(start)  # Init queue with the start node
    while not q.is_empty():
        # Get current node
        x, y, parent = q.remove()
        # Goal test
        if x == goal[0] and y == goal[1]: return (x, y, parent)
        # Check all vertical and horizontal neighbors
        for x0, y0 in ((x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)):
            # Out of bounds checks
            if x0 < 0 or y0 < 0: continue
            if x0 == len(maze) or y0 == len(maze[0]): continue
            # Expand the node
            if maze[x0][y0] == PATH:
                q.insert((x0, y0, (x, y, parent)))
                maze[x0][y0] = -1  # Show that this node has been expanded
    return None
class Animal_Queue(object):
    def __init__(self):
        self.dog_queue = Queue()
        self.cat_queue = Queue()
        self.time = 0

    def enqueue(self, animal):
        animal.order = self.time
        self.time += 1

        if animal.kind == 'dog':
            self.dog_queue.add(animal)
        else:
            self.cat_queue.add(animal)

    def dequeue_any(self):
        if self.dog_queue.front().order < self.cat_queue.front().order:
            self.dog_queue.remove()
        else:
            self.cat_queue.remove()

    def dequeue_dog(self):
        self.dog_queue.remove()

    def dequeue_cat(self):
        self.cat_queue.remove()

    def print_animal_queue(self):
        print '[',
        for i in range(self.dog_queue.size):
            print self.dog_queue.list[i].name,
        print ']'

        print '[',
        for i in range(self.cat_queue.size):
            print self.cat_queue.list[i].name,
        print ']'
def main():

    students = [Student(student_id) for student_id in range(1, 10)]

    print_queue = Queue()

    print("\n\t\tPrinter Initiated")

    for student in students:
        tasks_list = [Task(), Task()]
        student.addTasks(tasks_list)
        print_queue.add(student)

    while not bool(print_queue):

        student_tasks = print_queue.remove()
        tasks = student_tasks.tasks
        for task in range(len(tasks)):

            printer = Printer()

            print("\n\t---PRINTING!!--")
            if printer.isBusy():
                printer.task = tasks[task]
                printer.print()
                current_status = QueueStatus(print_queue, printer)
                print("Printing Student {0} task:{1}".format(
                    student_tasks.id, task + 1))
                print("Total pages: ", current_status[1])
                print("Average waiting time {0} min".format(current_status[0]))
                if printer.taskCompleted():
                    print("Current Task Print Completed")

            else:
                print(
                    "Printer is busy, will update you the status very shortly "
                )

    print("ALL TASKS HAVE PRINTED")
Example #21
0
def solveMaze(start, end, maze):

    q = Queue()
    q.insert(start)

    explored = []

    while not q.isEmpty():
        state = q.remove()
        explored.append(state)

        if state == end:
            path = findPath(explored)
            return path, explored

        neighbours = findAccessibleArea(state, maze)

        for neighbour in neighbours:
            if neighbour not in explored and neighbour not in q.contents():
                q.insert(neighbour)

    return [], []
Example #22
0
def check_if_binary_search_tree(root):
    """Using a Queue"""
    queue = Queue()
    queue.add(root)

    while queue.queue:
        node = queue.remove()
        print(node)
        if node.left:
            # If left node, check it is smaller
            if node.left.data < node.data:
                queue.add(node.left)
            else:
                return False
        if node.right:
            # If right node, check it is greater
            if node.right.data > node.data:
                queue.add(node.right)
            else:
                return False

    return True
Example #23
0
def serialize_tree(tree):
    tree_list = []
    queue = Queue()
    queue.add(tree)

    while queue.queue:
        node = queue.remove()
        if node is None:
            tree_list.append(-1)
        else:
            tree_list.append(node.data)

            if node.left:
                queue.add(node.left)
            else:
                queue.add(None)

            if node.right:
                queue.add(node.right)
            else:
                queue.add(None)

    return tree_list
Example #24
0
 def test_remove(self):
     q = Queue()
     q.add(3)
     q.add(4)
     q.add(6)
     self.assertEqual(q.remove(), 3)
Example #25
0
class Connection(object):
    """Abstracción de conexión. Maneja colas de entrada y salida de datos,
    y una funcion de estado (task). Maneja tambien el avance de la maquina de
    estados.
    """
    def __init__(self, fd, address=''):
        """Crea una conexión asociada al descriptor fd"""
        self.socket = fd
        self.task = None  # El estado de la maquina de estados
        self.input = Queue()
        self.output = Queue()
        # Esto se setea a true para pedir al proxy que desconecte
        self.remove = False
        self.address = address

    def fileno(self):
        """
        Número de descriptor del socket asociado.
        Este metodo tiene que existir y llamarse así
        para poder pasar instancias
        de esta clase a select.poll()
        """
        return self.socket.fileno()

    def direction(self):
        """
        Modo de la conexión, devuelve uno de las constantes DIR_*;
        también puede devolver None si el estado es el final
         y no hay datos para enviar.
        """
        # La cola de salida puede estar vacia por dos motivos:
        #   -1) Se enviaron todos los datos -> Remove es True
        #   -2) La cola de salida no esta lista AUN -> Sigue recibiendo
        if self.output.data == "":
            if self.remove:  # (1)
                return None  # El estado es el final
            else:  # (2)
                return DIR_READ  # Sigue recibiendo
        else:  # La cola de salida esta lista para enviarse
            return DIR_WRITE

    def recv(self):
        """
        Lee datos del socket y los pone en la cola de entrada.
        También maneja lo que pasa cuando el remoto se desconecta.
        Aqui va la unica llamada a recv() sobre sockets.
        """
        try:
            data = self.socket.recv(RECV_SIZE)  # Receive
            if data == "":  # El remoto se ha desconectado
                self.remove = True  # Hay que removerlo
            self.input.put(data)  # Encola los datos recibidos
        except socket_error:
            self.send_error(INTERNAL_ERROR, "Internal Error")
            self.remove = True

    def send(self):
        """Manda lo que se pueda de la cola de salida"""
        # Envia sended_size bytes
        sended_size = self.socket.send(self.output.data)
        # Elimina los datos enviados de la cola
        self.output.remove(sended_size)

    def close(self):
        """Cierra el socket. OJO que tambien hay que avisarle al proxy que nos
        borre.
        """
        self.socket.close()
        self.remove = True
        self.output.clear()

    def send_error(self, code, message):
        """Funcion auxiliar para mandar un mensaje de error"""
        logging.warning("Generating error response %s [%s]",
                        code, self.address)
        self.output.put("HTTP/1.1 %d %s\r\n" % (code, message))
        self.output.put("Content-Type: text/html\r\n")
        self.output.put("\r\n")
        self.output.put(
            "<body><h1>%d ERROR: %s</h1></body>\r\n" % (code, message))
        self.remove = True
class GraphAlgo:
    def __init__(self, problem):
        self.f = Queue()
        self.f.put(problem.initialState())
        self.e = []
        self.problem = problem
        self.pathCost = 0
        self.maxMemoryUsage = 0
        self.seenNodes = 0
        self.expandedNodes = 0
        self._depth = 0

    def showResult(self,
                   start,
                   pathCostNotCalculate=False,
                   bidirectionalNode=None
                   ):  #bidirectionalNode is for bidirectionalSearch
        path = []
        actions = []
        while start.parent != None:
            path.append(start.state)
            actions.append(start.parent['action'])
            start = start.parent['node']
        path.append(start.state)
        path.reverse()
        actions.reverse()
        if bidirectionalNode:
            del path[-1]
            while bidirectionalNode.parent != None:
                path.append(bidirectionalNode.state)
                actions.append(bidirectionalNode.parent['action'].invert())
                bidirectionalNode = bidirectionalNode.parent['node']
            path.append(bidirectionalNode.state)
        print('actions: ', actions)
        print('path: ', path)
        print('seen nodes: ', self.seenNodes)
        print('expanded nodes: ', self.expandedNodes)
        print('max memory usage: ', self.maxMemoryUsage)
        if pathCostNotCalculate:
            print('path cost: ', len(path))
        else:
            print('path cost: ', self.pathCost)

    def BFS(self):
        while True:
            if len(self.f.queue) == 0:
                print('f is empty!!!')
                return
            node = self.f.get()
            self.e.append(node)
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                child.parent = {'node': node, 'action': action}
                if child.state not in [
                        x.state for x in self.f.queue
                ] and child.state not in [x.state for x in self.e]:
                    if self.problem.isGoal(child):
                        self.seenNodes = self.f.qsize() + len(self.e) + 1
                        self.expandedNodes = len(self.e)
                        self.maxMemoryUsage = self.f.qsize() + len(self.e)
                        self.showResult(child, True)
                        return
                    else:
                        self.f.put(child)

    def DFS(self):
        if not self.recursivDFS(self.f.get()):
            print('not found!!!')

    def recursivDFS(self, node):
        self.seenNodes += 1
        self._depth += 1
        self.maxMemoryUsage = max(self.maxMemoryUsage, self._depth)
        if self.problem.isGoal(node):
            self.pathCost = self._depth
            self.showResult(node)
            return True
        else:
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                child.parent = {'node': node, 'action': action}
                result = self.recursivDFS(child)
                if result:
                    return True
            self._depth -= 1
            self.expandedNodes += 1
            return False

    def DFSGraphSearch(self):
        self.f = []
        self.f.append(self.problem.initialState())
        while True:
            if len(self.f) == 0:
                print('f is empty!!!')
                return
            node = self.f.pop()
            self.e.append(node)
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                child.parent = {'node': node, 'action': action}
                if child.state not in [
                        x.state for x in self.f
                ] and child.state not in [x.state for x in self.e]:
                    if self.problem.isGoal(child):
                        self.seenNodes = len(self.f) + len(self.e) + 1
                        self.expandedNodes = len(self.e)
                        self.maxMemoryUsage = len(self.f) + len(self.e)
                        self.showResult(child, True)
                        return
                    else:
                        self.f.append(child)

    def depthLimitedSearch(self, limit):  #DFS with Depth-Limited-Search
        if not self.recursivDLS(self.f.get(), limit):
            print('not found!!!')

    def recursivDLS(self, node, limit):
        limit -= 1
        self.seenNodes += 1
        self._depth += 1
        self.maxMemoryUsage = max(self.maxMemoryUsage, self._depth)
        if self.problem.isGoal(node):
            self.pathCost = self._depth
            self.showResult(node)
            return True
        elif limit == 0:
            self._depth -= 1
            return False
        else:
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                child.parent = {'node': node, 'action': action}
                result = self.recursivDLS(child, limit)
                if result:
                    return True
            self._depth -= 1
            self.expandedNodes += 1
            return False

    def iterativeDeepeningSearch(self):
        limit = 0
        node = self.f.get()
        while self.maxMemoryUsage >= limit:
            limit += 1
            if self.recursivDLS(node, limit):
                return
            self._depth = 0

    def bidirectionalSearch(self, goal):
        g = Queue()
        g.put(goal)
        h = []
        while True:
            if len(self.f.queue) == 0:
                print('f is empty!!!')
                return
            if len(g.queue) == 0:
                print('g is empty!!!')
                return
            subscribe = next(
                (node.state for node in self.f.queue
                 if node.state in [node.state for node in g.queue]), None)
            if (subscribe):
                self.seenNodes = self.f.qsize() + len(
                    self.e) + g.qsize() + len(h)
                self.expandedNodes = len(self.e) + len(h)
                self.maxMemoryUsage = self.f.qsize() + len(
                    self.e) + g.qsize() + len(h)
                self.showResult(
                    next(node for node in self.f.queue
                         if node.state == subscribe), True,
                    next(node for node in g.queue if node.state == subscribe))
                return

            node1 = self.f.get()
            self.e.append(node1)
            for action in self.problem.actions(node1):
                child1 = self.problem.result(node1, action)
                child1.parent = {'node': node1, 'action': action}
                if child1.state not in [
                        x.state for x in self.f.queue
                ] and child1.state not in [x.state for x in self.e]:
                    self.f.put(child1)

            subscribe = next(
                (node.state for node in self.f.queue
                 if node.state in [node.state for node in g.queue]), None)
            if (subscribe):
                self.seenNodes = self.f.qsize() + len(
                    self.e) + g.qsize() + len(h)
                self.expandedNodes = len(self.e) + len(h)
                self.maxMemoryUsage = self.f.qsize() + len(
                    self.e) + g.qsize() + len(h)
                self.showResult(
                    next(node for node in self.f.queue
                         if node.state == subscribe), True,
                    next(node for node in g.queue if node.state == subscribe))
                return

            node2 = g.get()
            h.append(node2)
            for action in self.problem.actions(node2):
                child2 = self.problem.result(node2, action)
                child2.parent = {'node': node2, 'action': action}
                if child2.state not in [
                        x.state for x in g.queue
                ] and child2.state not in [x.state for x in h]:
                    g.put(child2)

    def uniformCostSrearch(self):
        self.f = []
        heapq.heappush(self.f, (0, self.problem.initialState()))
        while True:
            if not self.f:
                print("f is empty!!!")
                return
            myTuple = heapq.heappop(self.f)
            node = myTuple[1]
            nodePathCost = myTuple[0]
            if self.problem.isGoal(node):
                self.seenNodes = len(self.f) + len(self.e) + 1
                self.expandedNodes = len(self.e)
                self.maxMemoryUsage = len(self.f) + len(self.e) + 1
                self.pathCost = nodePathCost
                self.showResult(node)
                return

            self.e.append(node)
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                pathCost = nodePathCost + self.problem.cost(node, action)
                child.parent = {'node': node, 'action': action}
                if (child.state not in [
                        x[1].state for x in self.f
                ]) and (child.state not in [x.state for x in self.e]):
                    heapq.heappush(self.f, (pathCost, child))
                else:
                    temp = next(
                        (x for x in self.f
                         if (x[1].state == child.state and x[0] > pathCost)),
                        None)
                    if temp:
                        self.f.remove(temp)
                        heapq.heappush(self.f, (pathCost, child))

    def AStar(self):
        self.f = []
        heapq.heappush(self.f, (self.problem.h(
            self.problem.initialState()), self.problem.initialState()))
        while True:
            if not self.f:
                print("f is empty!!!")
                return
            myTuple = heapq.heappop(self.f)
            node = myTuple[1]
            nodePathCost = myTuple[0]
            if self.problem.isGoal(node):
                self.seenNodes = len(self.f) + len(self.e) + 1
                self.expandedNodes = len(self.e)
                self.maxMemoryUsage = len(self.f) + len(self.e) + 1
                self.pathCost = nodePathCost - self.problem.h(node)
                self.showResult(node)
                return

            self.e.append(node)
            for action in self.problem.actions(node):
                child = self.problem.result(node, action)
                pathCost = nodePathCost - self.problem.h(
                    node) + self.problem.cost(node,
                                              action) + self.problem.h(child)
                child.parent = {'node': node, 'action': action}
                if (child.state not in [
                        x[1].state for x in self.f
                ]) and (child.state not in [x.state for x in self.e]):
                    heapq.heappush(self.f, (pathCost, child))
                else:
                    temp = next(
                        (x for x in self.f
                         if (x[1].state == child.state and x[0] > pathCost)),
                        None)
                    if temp:
                        self.f.remove(temp)
                        heapq.heappush(self.f, (pathCost, child))
Example #27
0
class Connection(object):
    """
    Abstracción de conexión. Maneja colas de entrada y salida de datos,
    y una función de estado (task). Maneja también el avance de la máquina de
    estados.
    """
    def __init__(self, fd, address=''):
        """
        Crea una conexión asociada al descriptor fd.
        """
        self.socket = fd
        self.task = None  # El estado de la maquina de estados.
        self.input = Queue()
        self.output = Queue()
        # Se setea a true para pedir al proxy que desconecte.
        self.remove = False
        self.address = address

    def fileno(self):
        """
        Número de descriptor del socket asociado.
        Este metodo tiene que existir y llamarse así para poder pasar
        instancias de esta clase a select.poll().
        """
        return self.socket.fileno()

    def direction(self):
        """
        Modo de la conexión, devuelve una de las constantes DIR_*; también
        puede devolver None si el estado es el final y no hay datos
        para enviar.
        """
        if self.output.data:
            return DIR_WRITE
        elif self.task is not None:
            return DIR_READ
        else:
            return None

    def recv(self):
        """
        Lee datos del socket y los pone en la cola de entrada.
        También maneja lo que pasa cuando el remoto se desconecta.
        Aquí va la única llamada a recv() sobre sockets.
        """
        try:
            data = self.socket.recv(BUFFSIZE)
            self.input.put(data)
            if len(data) == 0:
                self.remove = True
        except:
            self.remove = True

    def send(self):
        """
        Manda lo que se pueda de la cola de salida.
        """
        try:
            bytes_sent = self.socket.send(self.output.data)
            self.output.remove(bytes_sent)
        except:
            self.remove = True
            self.output.clear()

    def close(self):
        """
        Cierra el socket. También hay que avisarle al proxy que borre.
        """
        self.socket.close()
        self.remove = True
        self.output.clear()

    def send_error(self, code, message):
        """
        Función auxiliar para mandar un mensaje de error.
        """
        logging.warning("Generating error response %s [%s]", code,
                        self.address)
        self.output.put("HTTP/1.1 %d %s\r\n" % (code, message))
        self.output.put("Content-Type: text/html\r\n")
        self.output.put("\r\n")
        self.output.put("<body><h1>%d ERROR: %s</h1></body>\r\n" %
                        (code, message))
        self.remove = True
Example #28
0
    for cc in range(M):
        tmp = map(int, f.readline().strip().split(" "))
        for j in range(tmp[0]):
            mi, fl = tmp[j * 2 + 1] - 1, tmp[j * 2 +
                                             2]  # milkshake_index, flavour
            m_prefs[mi].add(cc)
            if fl == 0:
                c_prefs[cc][0] += 1
            elif fl == 1:
                c_prefs[cc][1] = mi
        if c_prefs[cc][0] == 0:  # Unsatisfied
            q.add(cc)

    while not q.isEmpty():
        cc = q.remove()  # unsatisfied customer
        batch[c_prefs[cc][1]] = 1
        sat_ones.add(cc)  # satisfied
        for kk in m_prefs[c_prefs[cc][1]]:
            if kk in sat_ones:  # Customer kk already satisfied
                continue
            if c_prefs[kk][1] != -1:  # Customer contains One
                if c_prefs[kk][1] == c_prefs[cc][1]:  # One exists at the pos
                    sat_ones.add(kk)
                elif c_prefs[kk][0] == 1:  # exactly 'One' and 'Zero'
                    q.add(kk)  # Add to queue
            elif c_prefs[kk][0] == 1:  # If just one 'zero'
                batch = "IMPOSSIBLE"
                q.remove_all()
                break
            c_prefs[kk][0] -= 1
Example #29
0
        # print '%6i       %7s        %8i    %8s    ' %(elevator.clock, 'A', elevator.floor, elevator.direction) , stops_to_string(stops) , '    ' , order.all()
        while len(stops) != 0:
            elevator.move()
            clean_coordinates()
            if elevator.floor in stops:
                clean_coordinates()
                stops.remove(elevator.floor)
                # print 'B', stops, elevator.direction, elevator.floor, order.all()
                # print '%6i       %7s        %8i    %8s    ' %(elevator.clock, 'B', elevator.floor, elevator.direction) , stops_to_string(stops) , '    ' , order.all()
                for passenger in session.query(Passenger).filter_by(destination_floor_id = elevator.floor):
                    passenger.finished = True
                    passenger.stop = passenger.start + passenger.waiting_time - 2
                for passenger in session.query(Passenger).filter_by(origin_floor_id = elevator.floor, direction = elevator.direction):
                    passenger.in_elevator = True
                    if order.has('%i%s' %(passenger.origin_floor_id,passenger.direction[0])):
                        order.remove('%i%s' %(passenger.origin_floor_id,passenger.direction[0]))
                stops = get_stops(stops)
                # print 'C', stops, elevator.direction, elevator.floor, order.all()
                # print '%6i       %7s        %8i    %8s    ' %(elevator.clock, 'C', elevator.floor, elevator.direction) , stops_to_string(stops) , '    ' , order.all()





for passenger in session.query(Passenger).filter_by(finished=True):
    print passenger.origin_floor, passenger.destination_floor, passenger.waiting_time, (passenger.start, passenger.stop)




Example #30
0
# -*- coding: utf-8 -*-

from queue import Queue
from stack import Stack

pilha_s = Stack()

# Alimentando a pilha:
for _ in range(4):
    elemento = input("Adicione algo à pilha: ")
    pilha_s.push(elemento)

# Invertendo a pilha com uma fila:
fila = Queue()

for _ in range(len(pilha_s)):
    fila.insert(pilha_s.pop())

# Nova pilha com valores invertidos
pilha_invertida = Stack()

for _ in range(len(fila)):
    pilha_invertida.push(fila.remove())

# Mostra nova pilha com os valores da primeira invertidos.
print(pilha_invertida)
from stack import Stack
from queue import Queue

if __name__ == '__main__':
    print 'Stack'
    stack = Stack()

    name = 'Maikel Maciel Ronnau'
    [stack.push(x) for x in name]

    for x in name:
        print stack.pop().data,

    print
    print '\nQueue'
    queue = Queue()

    name = 'Maikel Maciel Ronnau'
    [queue.add(x) for x in name]

    for x in name:
        print queue.remove().data,
    def RR(self):
        sorted_on_arrival_time = Queue(maxsize=len(self.all_proccess))
        #ititial time and burst_time
        self.time = 0
        self.total_burst_time = 0

        sorted_on_arrival_time = self.all_proccess[:]
        sorted_on_arrival_time.sort(key=lambda c: c.arrival_time,
                                    reverse=False)

        while (not self.ready_queue.empty()
               or len(sorted_on_arrival_time) != 0):

            if (self.ready_queue.empty()):
                p = sorted_on_arrival_time[0]
                self.time = p.getArrivalTime()
                self.ready_queue.put(p)
                sorted_on_arrival_time.remove(p)

            p = self.ready_queue.get()

            if (p.getStartTime() == -1):
                p.setStartTime(self.time)
            if (p.getRemainingTime() > 5):
                self.time = self.time + 5
                self.total_burst_time = self.total_burst_time + 5
                p.setRemainingTime(p.getRemainingTime() - 5)
            else:
                self.time += p.getRemainingTime()
                self.total_burst_time += p.getRemainingTime()
                p.setRemainingTime(0)
                p.setEndTime(self.time)

            tmp = sorted_on_arrival_time[:]
            for process in tmp:
                if (process.arrival_time <= self.time):
                    self.ready_queue.put(process)
                    sorted_on_arrival_time.remove(process)
            if (not p.isFinished()):
                self.ready_queue.put(p)

        #printAllProcess()

        # evaluate the CPU variables AWT, ATT, ART, Throughput, Utilization
        self.average_waiting_time = sum(
            [x.getWaittingTime()
             for x in self.all_proccess]) / len(self.all_proccess)
        self.average_turnaround_time = sum(
            [x.getTurnaroundTime()
             for x in self.all_proccess]) / len(self.all_proccess)
        self.average_response_time = sum(
            [x.getResponseTime()
             for x in self.all_proccess]) / len(self.all_proccess)
        self.throughput = len(self.all_proccess) / self.time
        self.cpu_utilization = self.total_burst_time / self.time

        #print all CPU variables
        print("RR:")
        print("Avg. W.T.: ", self.average_waiting_time)
        print("Avg. T.T.: ", self.average_turnaround_time)
        print("Avg. R.T: ", self.average_response_time)
        print("Throughput: ", self.throughput)
        print("CPU Utilization: ", self.cpu_utilization)
Example #33
0
result = q.insert(-1)
assert (result == True)
assert (not q.is_empty())
assert (q.__str__() == "-1 7 5")

result = q.insert(20)
assert (result == False)
assert (not q.is_empty())
assert (q.__str__() == "-1 7 5")

result = q.insert(33)
assert (result == False)
assert (not q.is_empty())
assert (q.__str__() == "-1 7 5")

x = q.remove()
assert (not q.is_empty())
assert (q.__str__() == "-1 7")
assert (x == 5)

x = q.remove()
assert (not q.is_empty())
assert (q.__str__() == "-1")
assert (x == 7)

q.insert(11)
assert (not q.is_empty())
assert (q.__str__() == "11 -1")

x = q.remove()
assert (not q.is_empty())