コード例 #1
0
    def __str__(self):
        queue = Queue()
        graph_string = ""

        print("Searching WUG")

        for node in self.nodes:
            self.set_all_nodes_unvisited()
            queue.empty()
            queue.add(node)
            node_string = ""

            while not queue.is_empty():
                current_node = queue.poll()

                if current_node.is_visited():
                    continue

                current_node.set_visited(True)
                node_string += str(current_node) + "\n\t"

                for edge in current_node.get_edges():
                    if not edge.get_node().is_visited():
                        node_string += str(edge.get_weight()) + " -> " + str(
                            edge.get_node()) + "\n\t"

            if node_string != "":
                graph_string += node_string + "\n"

        return graph_string
コード例 #2
0
ファイル: Graph.py プロジェクト: crain9412/pyalgos
    def __str__(self):
        queue = Queue()
        graph_string = ""

        for node in self.nodes:
            self.set_all_nodes_unvisited()
            queue.empty()
            queue.add(node)
            node_string = ""

            while not queue.is_empty():
                current_node = queue.poll()

                if current_node.is_visited():
                    continue

                current_node.set_visited(True)
                node_string += str(current_node) + " -> "

                for adjacent_node in current_node.get_adjacent_nodes():
                    if not adjacent_node.is_visited():
                        queue.add(adjacent_node)

            if node_string != "":
                graph_string += node_string[:-4] + "\n"

        return graph_string
コード例 #3
0
ファイル: AnimalQueue.py プロジェクト: 5cmpersec/ctci
class AnimalQueue(object):
    def __init__(self):
        self.cat_queue = Queue()
        self.dog_queue = Queue()
        self.time = 0

    def enqueue(self, animal):
        if type(animal) is Dog:
            self.dog_queue.add(animal)
        elif type(animal) is Cat:
            self.cat_queue.add(animal)
        else:
            raise ValueError("invalid type")
        animal.order = self.time
        self.time += 1

    def dequeueDog(self):
        return self.dog_queue.remove()

    def dequeueCat(self):
        return self.cat_queue.remove()

    def dequeueAny(self):
        if self.dog_queue.isEmpty():
            return self.dequeueCat()
        elif self.cat_queue.isEmpty():
            return self.dequeueDog()

        topDog = self.dog_queue.peek()
        topCat = self.cat_queue.peek()
        if topDog.order < topCat.order:
            return self.dequeueDog()
        else:
            return self.dequeueCat()
コード例 #4
0
def test_peeking_the_queue():

    q = Queue()

    q.add("hello")
    q.add("blob")

    assert q.peek().value == "hello"
コード例 #5
0
ファイル: TreeHelper.py プロジェクト: mhemendra/Algos
def breadthFirst(tree):
    queue = Queue()
    queue.add(tree)
    while not (queue.isEmpty()):
        node = queue.remove()
        print(node.data)
        children = node.getChildren()
        for child in children:
            queue.add(child)
コード例 #6
0
def test_adding_item_into_queue():

    q = Queue()

    q.add("hello")
    assert q._first.value == "hello"
    assert q._last.value == "hello"

    q.add("blob")
    assert q._first.value == "hello"
    assert q._last.value == "blob"
コード例 #7
0
def test_removing_item_from_the_queue():

    q = Queue()

    q.add("hello")
    q.add("blob")

    assert q.remove().value == "hello"
    assert q.remove().value == "blob"
    with pytest.raises(AttributeError) as e:
        q.remove()
    assert str(e.value) == "EmptyQueueError"
コード例 #8
0
class QueueTest(TestCase):
    def setUp(self):
        self.queue = Queue()

    def test_add(self):
        """tests the add function of the Queue class"""
        self.queue.add(1)
        self.assertEqual([1], self.queue.queue)

    def test_remove(self):
        """tests the remove function of the Queue class"""
        a = self.queue.queue[0]
        self.assertEqual(a, self.queue.remove())
コード例 #9
0
 def levelOrder(self, a):
     q = Queue()
     r = a
     while r is not None:
         print(r.root.data)
         if r.root.left is not None:
             q.add(r.root.left)
         if r.root.right is not None:
             q.add(r.root.right)
         if q.isEmpty():
             print("empty")
             r = None
         else:
             r = q.delete()
コード例 #10
0
    def bfs(self, index):
        root = self.__nodes[index]
        queue = Queue()
        queue.add(root)
        root.marked = True
        while not queue.is_empty():
            remove_node = queue.remove()
            for n in remove_node.adjacent:
                if not n.marked:
                    n.marked = True
                    queue.add(n)

            visit(remove_node)
        print()
コード例 #11
0
ファイル: 08_bst_search.py プロジェクト: kawael/training
 def levelOrder(self,a):
     q = Queue()
     r = a
     while r is not None:
         print(r.root.data)
         if r.root.left is not None:
             q.add(r.root.left)
         if r.root.right is not None:
             q.add(r.root.right)
         if q.isEmpty():
             print("empty")
             r = None
         else:
             r = q.delete()
コード例 #12
0
ファイル: Main.py プロジェクト: sachinpc1993/DSinPython
def testQueue():
    a = Queue()

    #Testing isEmpty()
    print(a.isEmpty())

    #Testing adding
    for i in range(10):
        a.add(i)
        a.displayQueue()

    #Testing removing
    a.remove()
    a.displayQueue()
コード例 #13
0
def BreathFistSearch(root):
    if root is None:
        return
    from Queue import Queue
    queue = Queue()
    root.state = State.VISITING
    queue.add(root)
    while queue.isEmpty() is False:
        node = queue.remove()
        for child in node.adj:
            if child.state is State.UNVISITED:
                child.state = State.VISITING
                queue.add(child)
        visit(node)
        node.state = State.VISITED
コード例 #14
0
class AnimalShelter():
    def __init__(self):
        self.cats = Queue()
        self.dogs = Queue()

    def enqueue(self, animal):
        if animal.__class__ == Cat:
            self.cats.add(animal.name)
        else:
            self.dogs.add(animal.name)

    def dequeueAny(self):
        if not self.dogs.isEmpty():
            return self.dequeueDog()
        else:
            self.dequeueCat()

    def dequeueCat(self):

        if self.cats.isEmpty():
            return None
        else:
            cat = self.cats.peek()
            self.cats.remove()
            return cat

    def dequeueDog(self):
        if self.dogs.isEmpty():
            return None
        else:
            dog = self.dogs.peek()
            self.dogs.remove()
            return dog

    def print_shelter(self):
        print()
        print('Our Cats : ')
        for i in self.cats.my_queue:
            print(i)
        print()
        print('Our Dogs : ')
        for i in self.dogs.my_queue:
            print(i)
        print()
コード例 #15
0
ファイル: PathFinder.py プロジェクト: romrell4/470-AI
    def doAStar(self, gridMap, start, goal):
            print "AStar"

	    #Create queue with only root node
	    q = Queue()
            begin = finish = None
            closest_start = closest_end = float("inf")
            for point in gridMap:
                dist_start = start.distanceTo(point)
                dist_end = goal.distanceTo(point)
                if dist_start < closest_start:
                    closest_start = dist_start
                    begin = point
                if dist_end < closest_end:
                    closest_end = dist_end
                    finish = point
	    q.add(Node(begin, Cost(point.distanceTo(finish), 0), []))

	    bestSoFar = float("inf")
	    bestNode = None
	    while(True):
	        parent = q.pop()
	        if (parent == None or parent.cost.f > bestSoFar):
		    break

	        for child in parent.point.accessiblePoints:
		    if parent.hasPointInPath(child):
		        continue

		    g = parent.cost.g + parent.point.distanceTo(child)
		    h = child.distanceTo(finish)

		    cost = Cost(g + h, g)
		    node = Node(child, cost, parent.path + [parent.point])
		    q.add(node)

		    if (h == 0 and bestSoFar > g):
		        bestSoFar = g
		        bestNode = node


	    if bestNode == None:
	        return None
	    return bestNode.path + [goal]
コード例 #16
0
    def doAStar(self, gridMap, start, goal):
        print "AStar"

        #Create queue with only root node
        q = Queue()
        begin = finish = None
        closest_start = closest_end = float("inf")
        for point in gridMap:
            dist_start = start.distanceTo(point)
            dist_end = goal.distanceTo(point)
            if dist_start < closest_start:
                closest_start = dist_start
                begin = point
            if dist_end < closest_end:
                closest_end = dist_end
                finish = point
        q.add(Node(begin, Cost(point.distanceTo(finish), 0), []))

        bestSoFar = float("inf")
        bestNode = None
        while (True):
            parent = q.pop()
            if (parent == None or parent.cost.f > bestSoFar):
                break

            for child in parent.point.accessiblePoints:
                if parent.hasPointInPath(child):
                    continue

                g = parent.cost.g + parent.point.distanceTo(child)
                h = child.distanceTo(finish)

                cost = Cost(g + h, g)
                node = Node(child, cost, parent.path + [parent.point])
                q.add(node)

                if (h == 0 and bestSoFar > g):
                    bestSoFar = g
                    bestNode = node

        if bestNode == None:
            return None
        return bestNode.path + [goal]
コード例 #17
0
    def BFS(self):
        if len(self.nodes) == 0:
            return []

        root = self.nodes[0]
        visited = set([root])
        Q = Queue()
        Q.add(root)
        BfsResult = []

        while Q.size() > 0:
            QueueHead = Q.remove()
            BfsResult.append(QueueHead)
            for neighbour in QueueHead.neighbours:
                if neighbour not in visited:
                    Q.add(neighbour)
                    visited.add(neighbour)

        return BfsResult
コード例 #18
0
ファイル: RouteBetweenNodes.py プロジェクト: 5cmpersec/ctci
def RouteBetweenNodes(G, A, B):
    from Queue import Queue
    if A == B:
        return True
    queue = Queue()
    for u in G.nodes:
        u.state = State.UNVISITED

    A.state = State.VISITING
    queue.add(A)
    while queue.isEmpty() is False:
        node = queue.remove()
        for v in node.adj:
            if v == B:
                return True
            elif v.state == State.UNVISITED:
                v.state = State.VISITING
                queue.add(v)
        node.state = State.VISITED
    return False
コード例 #19
0
def main():
    queue = Queue(10)
    queue.add("Douglas")
    queue.add("Schneider")
    queue.add("Serena")

    print(queue.showFull())
    print(queue.show())
コード例 #20
0
class Broker(object):
    def __init__(self, send_ws_message):
        self.message_queue = Queue()
        self.connections = ConnectionMap()
        self.send = send_ws_message

    def listen_on_queue(self):
        while True:
            try:
                message = self.message_queue.pop()
                if message is not None:
                    self._broadcast_message(message)
                    print 'message broker got:', message.value
                time.sleep(0.1)
            except Exception as e:
                print "Something went wrong ", e

    def _broadcast_message(self, message):
        for connection in self.connections.get_hash_list():
            while connection is not None:
                try:
                    self.send(connection.connection, message.value)
                except Exception as e:
                    print "exception in broadcasting to this connection, closing it ", e
                    connection.connection.close()
                    self.connections.remove(connection.key)
                connection = connection.next_node

    def add_connection(self, address, connection):
        self.connections.put(address, connection)

    def remove_connection(self, address):
        self.connections.remove(address)

    def add_message_to_queue(self, message):
        self.message_queue.add(message)
コード例 #21
0
ファイル: Graph.py プロジェクト: crain9412/pyalgos
    def breadth_first_search(self, source, target):
        queue = Queue()
        found = None

        self.set_all_nodes_unvisited()
        queue.empty()
        queue.add(source)

        while not queue.is_empty():
            current_node = queue.poll()

            if current_node.is_visited():
                continue

            if current_node.data == target:
                return target

            current_node.set_visited(True)

            for adjacent_node in current_node.get_adjacent_nodes():
                if not adjacent_node.is_visited():
                    queue.add(adjacent_node)

        return found
コード例 #22
0
def clone_graph(source):
    q = Queue()
    q.put(source)
    hm = {}
    hm[source] = Node(source.data)

    while not q.empty():
        node = q.get()
        clone_node = hm.get(node)

        if len(node.neighbours) != 0:
            for neighbour in node.neighbours:

                clone_neighbour = hm.get(neighbour)

                if clone_neighbour is None:
                    q.add(neighbour)

                    clone_neighbour = Node(neighbour.data)
                    hm.put(neighbour, clone_neighbour)

                clone_node.neighbours.append(clone_neighbour)

    return hm[source]
コード例 #23
0
    def bfs(self):
        queue = Queue()

        queue.add(self.root)

        while(queue.length() > 0):
            p = queue.pop()

            print(p.val),

            if p.left != None:
                queue.add(p.left)

            if p.right != None:
                queue.add(p.right)
コード例 #24
0
                    timeout=1,
                    writeTimeout=1)
if tes.isOpen():
    while True:
        ligne = tes.readline()
        if ligne.decode("utf-8").startswith('{'):
            """
				strore in influxdb part
			 
			
			"""
            ligne.decode("utf-8").replace("\r\n", "")
            text = json.loads(ligne)
            #print(text["temperature"])
            text["date"] = str(
                datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'))
            result, ret = client.publish("/topic/temperature",
                                         text["temperature"])
            result1, ret1 = client.publish("/topic/humidity", text["humidity"])

            result1, ret1 = client.publish("/topic/all", str(text))

            if result == 0:
                if not queue.isEmpty():
                    queue.sendAll(client)
                print("Published")
            else:
                queue.add(ligne)
                #dataToStore.append(ligne)
                print("offline")
client.loop_stop()
コード例 #25
0
from Stack import Stack
from Queue import Queue

s = Stack()
s.push(1)
s.push(2)
s.push(3)

q = Queue()
q.add(1)
q.add(2)
q.add(3)

print("Stack 'contains' tests: %r, %r, %r, %r" %
      (s.contains(0), s.contains(1), s.contains(2), s.contains(3)))
print("Queue 'contains' tests: %r, %r, %r, %r" %
      (q.contains(0), q.contains(1), q.contains(2), q.contains(3)))

s.pop()
s.pop()
s.pop()
print("Empty stack 'contains' test: %r" % s.contains(4))

q.remove()
q.remove()
q.remove()
print("Empty queue 'contains' test: %r" % q.contains(4))
コード例 #26
0
                break

    elif (listtype == '2' or listtype == 'queue'):
        head = node()
        queue = Queue()
        option = 0
        while option != 'exit':
            printQueue(head)
            option = optionQueue()

            if option == '1':
                [name, titles
                 ] = input('Enter team and their titles e.g. (name, titles): '
                           ).split(', ')
                data = footballTeam(name, titles)
                head = queue.add(head, data)
                os.system('clear')

            elif option == '2':
                head = queue.remove(head)
                os.system('clear')

            elif option == '3':
                os.system('clear')
                print(f'\nIs the Queue empty? {queue.isEmpty(head)}')

            elif option == '4':
                os.system('clear')
                print(f'\nSize of the current Queue is {queue.size(head)}')

            elif option == '5':
コード例 #27
0
ファイル: Maze.py プロジェクト: PLAZMAMA/PathFinder
    def find_path(self, s, e):
        """finds the path from s to e and updates the grid with the found path and returns if it was able to reach the end"""
        #initializing the queues
        rq = Queue()
        cq = Queue()

        #initially marking reached end as false (used to know if the end is reachable)
        reached_end = False

        #initializing the visited array to keep track of visited nodes and a prev array to keep track of the path
        visited = np.zeros((self.grid_size[0], self.grid_size[1]), dtype = np.bool)
        prev = self.create_list((self.grid_size[0], self.grid_size[1], 2), None)
        
        #added the starting row position to the row queue and starting column position to the column queue
        rq.add(s[0])
        cq.add(s[1])

        #marked the first positions as true
        visited[s[0]][s[1]] = True

        #running while the queues is not empty (only put one because the queue will always be the same size)
        while len(cq.queue) > 0:
            #removes the nodes coordinates from the queues and puts them into the variables r, c
            r = rq.remove()
            c = cq.remove()

            #checks if the node location is the same as the end location (checks if it reached the end)
            if r == e[0] and c == e[1]:
                reached_end = True
                break
            
            #adding to it the appropriate neighbors to the queues and the visited and prev arrays
            if c + 2 < self.grid_size[1] and np.all(self.grid[r][c + 1] == [10, 206, 245]) and visited[r][c + 2] == False:
                rq.add(r)
                cq.add(c + 2)
                visited[r][c + 2] = True
                prev[r][c + 1] = [r, c]
                prev[r][c + 2] = [r, c + 1]
            if c - 2 >= 0 and np.all(self.grid[r][c - 1] == [10, 206, 245]) and visited[r][c - 2] == False:
                rq.add(r)
                cq.add(c - 2)
                visited[r][c - 2] = True
                prev[r][c - 1] = [r, c]
                prev[r][c - 2] = [r, c - 1]
            if r - 2 >= 0 and np.all(self.grid[r - 1][c] == [10, 206, 245]) and visited[r - 2][c] == False:
                rq.add(r - 2)
                cq.add(c)
                visited[r - 2][c] = True
                prev[r - 1][c] = [r, c]
                prev[r - 2][c] = [r - 1, c]
            if r + 2 < self.grid_size[0] and np.all(self.grid[r + 1][c] == [10, 206, 245]) and visited[r + 2][c] == False:
                rq.add(r + 2)
                cq.add(c)
                visited[r + 2][c] = True
                prev[r + 1][c] = [r, c]
                prev[r + 2][c] = [r + 1, c]
        
        self.create_path(prev, e, reached_end)
        return(reached_end)
コード例 #28
0
    while GPIO.input(pin) == GPIO.LOW:
        count += 1

    return count


pygame.mixer.music.play()
pygame.mixer.music.pause()

played_at = None

try:
    q = Queue(max_length=20)
    while True:
        t = light_time(light_pin)
        q.add(t)
        print(q.average())

        if q.average() > limit:
            if not playing:
                pygame.mixer.music.unpause()
                #pygame.mixer.music.rewind()
                playing = True
                played_at = datetime.now()
        else:
            pygame.mixer.music.pause()
            playing = False
        
        if played_at:
            diff = datetime.now() - played_at
            diff_in_hours = diff.total_seconds() / 3600
コード例 #29
0
    ub = list_linked.size
    found = False
    while found == False:
        if ub < lb:
            print("Data not found.")
            return None
            break
        mid = int(lb + (ub - lb) / 2)
        temp = list_linked.head
        for i in range(mid):
            temp = temp.next
        if temp.name == item:
            print("Found data " + str(item) + " at position " + str(mid + 1))
            found = True
            return mid
            #print("e2")
        if temp.name < item:
            lb = mid + 1
            print("e3")
        if temp.name > item:
            ub = mid - 1
            print("e4")


qu = Queue()
for i in range(100):
    qu.add(Node(random.randint(1, 100)))

BubbleSort(qu)
BinarySearch(qu, 5)
コード例 #30
0
ファイル: usercase.py プロジェクト: jiahut/datastructures
s.pop()  
trrce(s)
s.pop()
trrce(s)
s.pop()
trrce(s)
s.pop()
trrce(s)
s.pop()
trrce(s)
print("isEmpty? ",s.isEmpty())

print("--------------Queue----------------")

q = Queue(5)
q.add(1)
trrce(q)
q.add(2)
trrce(q)
q.add(3)
trrce(q)
q.add(4)
trrce(q)
q.add(5)
trrce(q)
print("first = ", q.first())
print("last = ", q.last())
print("isFull? ", q.isFull())
q.remove()
trrce(q)
q.remove()
コード例 #31
0
print("Conveyor Belt Generated")
print("Input your commands")
print(" 0XXXX \n"
      "Retrieve a product with ID XXXX \n"
      "1XXXX \n"
      "Store a product with ID XXXX \n"
      "2XY00 \n"
      "Sort warehouse X at row Y \n"
      "30000 \n"
      "Retrieve a product from the conveyor belt \n"
      "40000 \n"
      "Output information on all of the warehouses \n"
      "5XXXX \n"
      "Search for a product ID XXXX \n"
      "9XXXXYYYY \n"
      "Manually put a product ID XXXX at position YYYY \n")
newcom = True
while newcom:
    comm = input("Please enter command\n")
    commandQue.add(Node(comm))
    yesno = ''
    while yesno != 'y' and yesno != 'n':
        yesno = input("Would you like to enter another command? y/n\n")
        yesno = yesno.lower()
    if yesno == 'n':
        newcom = False
#Execution
for i in range(commandQue.size):
    executeCommand(commandQue.remove())
コード例 #32
0
ファイル: Recursion.py プロジェクト: mhemendra/Algos
        q1.add(top)
    return q1

    #return s2


def paintFill(row, col, arr=[]):
    if row == 0 or col == 0:
        return
    else:
        if not (arr.__contains__([row, col])):
            arr.append([row, col])
        paintFill(row - 1, col, arr)
        paintFill(row, col - 1, arr)
        return arr


grid = np.zeros([4, 4])
grid[0, 1] = 1
#roboGrid(grid, 3, 3)
q1 = Queue()
for i in range(5):
    q1.add(i)

output = reverseQueue(q1)
#print(output.pop())

while not output.isEmpty():
    print(output.remove())

print()
コード例 #33
0
ファイル: Operation.py プロジェクト: nguyenquang0601/Python
class Operation:
  def __init__(self):
    self.IBSTree =  BSTree(None)
    self.IQueue = Queue()
  # Load file to data set
  def loadFile(self,file): 
    try:
      fh = open(file,"r")
      fh.readline()
      for line in fh:
        arr = list(line.rstrip().split(','))
        # New person
        person = Person(arr[0],arr[1],arr[2],arr[3])
        #  Add person to Tree
        self.IBSTree.insert(person)
      print("The file is loaded successfully!")
    except:
      print("File path is correct!")
  # Add person to dataset
  def addNewPerson(self):
    IDExist = True
    ID = None
    while IDExist:
      ID = input("Please insert the new ID:")
      #  Check ID is existed
      person = self.IBSTree.findPerson(ID)
      if person is None:
        IDExist = False
      else:
        print("This ID has been chosen, please choose anothor ID!")
    name = input("Please insert the Name:")
    birthplace = input("Please insert the Birthplace:")
    birthofDate = input("Please insert the Birth of Date:")
    person = Person(ID,name,birthofDate,birthplace)
    # Add to Tree
    self.IBSTree.insert(person)
    print("New ID:", person.ID)
    print("Name:", person.Name)
    print("Birthplace:",person.Birthplace)
    print("Date of birth:",person.DayofBirth)
    input("Please tyoe anything to come back to the main memu")

  # Inorder : Left to Right

  def InorderTraverse(self):
    lists = self.IBSTree.Inorder(self.IBSTree)
    print("ID | Name | Day of Birth | Birthplace")
    for person in lists:
      person.printDetail()
    input("Please tyoe anything to come back to the main memu")
  
  # Queue
  def Bfs(self):
    print("ID | Name | Day of Birth | Birthplace")
    if self.IBSTree is None:
      return 
    self.IQueue.add(self.IBSTree)
    # Loop Queue and Print
    while self.IQueue.peek() is not None:
      current_node = self.IQueue.remove()
      current_node.person.printDetail()
      if (current_node.left is not None):
        self.IQueue.add(current_node.left)
      if (current_node.right is not None):
        self.IQueue.add(current_node.right)
    input("Please tyoe anything to come back to the main memu")
  
  # Search Person
  def SearchbyID(self,ID):
    print("Search for ID = ",ID)
    person = self.IBSTree.findPerson(ID)
    if person is not None:
      print("ID | Name | Day of Birth | Birthplace")
      person.printDetail()
    else:
      print("The searched ID is not valid")
    input("Please tyoe anything to come back to the main memu")
  
  # Delete by ID
  def DeleteByID(self,ID):
    #Search Person
    personFound =  self.IBSTree.findPerson(ID)
    if personFound is not None:
      # Delete Person
      self.IBSTree.delete(self.IBSTree,ID)
      print("ID | Name | Day of Birth | Birthplace")
      personFound.printDetail()
    else:
      print("The searched ID is not valid")
    input("Please tyoe anything to come back to the main memu")