Exemple #1
0
def bfs(begin, end):
    dist = [[1 for _ in range(m)] for _ in range(n)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    dist[begin.x][begin.y] = 0
    q = Queue()
    q.enqueue(begin)
    while q:
        res = q.dequeue()
        flag = False
        for i in range(4):
            nx, ny = res.x + dx[i], res.y + dy[i]
            if 0 <= nx < n and 0 <= ny < m and a[nx][ny] != "#" and dist[nx][
                    ny] == 1:
                dist[nx][ny] = dist[res.x][res.y] + 1
                q.enqueue(Point(nx, ny))
                if nx == end.x and ny == end.y:
                    flag = True
                    break
        if flag:
            break
    if flag:
        print("Yes")
        return
    print("No")
Exemple #2
0
def radix_sorting_machine(num_list: list) -> list:
    # main_bin 设定
    main_bin = Queue()
    main_bin.items = num_list
    # 10个digit bin
    bin_dic = [None] * 10
    # 最大数字位计算
    max_digit = 0
    for i in num_list:
        current_len = len(str(i))
        if current_len > max_digit:
            max_digit = current_len
    # 逐位排序,便览各位
    for n in range(1, max_digit + 1):
        while not main_bin.isEmpty():  # 便览main_bin中的数
            current_num = main_bin.dequeue()
            current_num_copy = current_num
            # 计算倒数第n位的数字
            m = 1
            while m <= n:
                remainder = current_num_copy % 10
                current_num_copy = current_num_copy // 10
                m += 1
            # 存储进remainder号bin
            if bin_dic[remainder] == None:
                bin_dic[remainder]: Queue = Queue()
            bin_dic[remainder].enqueue(current_num)
            # 逐个digit bin弹出数字到main_bin
        for digit_bin in bin_dic:
            while digit_bin != None and not digit_bin.isEmpty():
                main_bin.enqueue(digit_bin.dequeue())

    return main_bin.items
Exemple #3
0
class SendSMS:
    def __init__(self, bulk_sms_provider):
        self.bulk_sms_provider = bulk_sms_provider
        self.msg_queue = Queue()

    def sms_queue(self, data):
        self.msg_queue.enqueue({'data': data})

    def send(self):
        while not self.msg_queue.isEmpty():
            msg = self.msg_queue.dequeue()
            bulk_sms_provider = self.bulk_sms_provider

            url = bulk_sms_provider.api_endpoint
            headers = literal_eval(
                bulk_sms_provider.headers)  #convert str to dict datatype
            data = msg['data']

            if bulk_sms_provider.username and bulk_sms_provider.password:
                response = requests.post(url=url,
                                         headers=headers,
                                         data=data,
                                         auth=(bulk_sms_provider.username,
                                               bulk_sms_provider.password))
            else:
                response = requests.post(url=url, headers=headers, data=data)

            return response
def main():
    words = get_words('dictionary.txt')
    my_queue = cQueue.Queue()
    py_queue = Queue()
    out_file = open('QueueComparisonData.csv', 'w')
    out_file.write('N,dll enq,pyds enq,dll deq,pyds deq\n')
    print('\tN\t\tdll enq\t\tpyds enq\tdll deq\t\tpyds deq')
    for x in range(20000, 181000, 20000):
        my_enqueue_start = time.time()
        for y in range(x):
            my_queue.enqueue(words[y])
        my_enqueue_time = time.time() - my_enqueue_start

        py_enqueue_start = time.time()
        for y in range(x):
            py_queue.enqueue(words[y])
        py_enqueue_time = time.time() - py_enqueue_start

        my_dequeue_start = time.time()
        for y in range(x):
            my_queue.dequeue()
        my_dequeue_time = time.time() - my_dequeue_start

        py_dequeue_start = time.time()
        for y in range(x):
            py_queue.dequeue()
        py_dequeue_time = time.time() - py_dequeue_start
        print('{:,d}\t\t{:.3G}\t\t{:.3G}\t\t{:.3G}\t\t{:.3G}'.format(
            x, my_enqueue_time, py_enqueue_time, my_dequeue_time,
            py_dequeue_time))
        out_file.write('{:d},{:.3G},{:.3G},{:.3G},{:.3G}\n'.format(
            x, my_enqueue_time, py_enqueue_time, my_dequeue_time,
            py_dequeue_time))
    out_file.close()
    plot_queue_data()
Exemple #5
0
def bfs(g, start):
    queue = Queue()
    queue.enqueue(start)
    start.setPred(None)
    while (queue.size() > 0):
        current = queue.dequeue()
        for nbr in current.getConnections():
            if nbr.getColor() == 'white':
                nbr.setColor('grey')
                nbr.setPred(current)
                queue.enqueue(nbr)
        current.setColor('black')
Exemple #6
0
def bfs(graph, start, debug=False):
      """
      Breadth First Search (BFS)
       Given a node in a graph, BFS will find all nodes connected to this
      node. The distance between nodes is measured in HOPS. It will find
      all nodes at distance 'k' before finding any nodes at a further
      distance. It will return the full list of connected nodes.
       PseudoCode:
       BFS(G,s)
       for each vertex u in V[G] - {s} do
        state[u] = WHITE
        predecessor[u] = nil
      state[s] = GRAY
      predecessor[s] = nil
      QUEUE = {s}
      while QUEUE != 0 do
        u = dequeue[Q]
        process vertex u as desired
        for each v in Adjacent[u] do
          process edge (u,v) as desired (e.g. distance[v] = distance[u] + 1)
          if state[v] = WHITE then
            state[v] = GRAY
            predecessor[v] = u
            enqueue[Q,v]
        state[u] = BLACK
      """
      result = []
      for v in graph.getVertices():
          a_vertex = graph.getVertex(v)
          a_vertex.__classname__ = 'MyVertex'
          a_vertex.setColor(MyVertex.WHITE)
          a_vertex.setDistance(0)
          a_vertex.setPred(None)

      start.setDistance(0)
      start.setPred(None)
      vertex_queue = Queue()
      vertex_queue.enqueue(start)
      while (vertex_queue.size() > 0):
          current_vertex = vertex_queue.dequeue()
          result.append(current_vertex)
          if debug:
              print(current_vertex)
          for v in current_vertex.getConnections():
              if v.getColor() == MyVertex.WHITE:
                  v.setColor(MyVertex.GRAY)
                  v.setDistance(current_vertex.getDistance() + 1)
                  v.setPred(current_vertex)
                  vertex_queue.enqueue(v)
          current_vertex.setColor(MyVertex.BLACK)
      return result
Exemple #7
0
def bfs(g, start):
    visited = []
    q = Queue()
    q.enqueue(start)
    visited.append(start)

    while not q.isEmpty():
        v = q.dequeue()
        for n in g.getVertex(v).getConnections():
            if n.id not in visited:
                q.enqueue(n.id)
                visited.append(n.id)

    return visited
Exemple #8
0
    def pop(self):
        q2 = Queue()
        n = 0
        x = None

        while not self.q1.isEmpty():
            x = self.q1.dequeue()
            # print(x)
            q2.enqueue(x)
            n += 1
            
        for i in range(n-1):
            self.q1.enqueue(q2.dequeue())
            
        return x
Exemple #9
0
def bfs(begin):  #x,y为初始点的坐标
    q = Queue()
    q.enqueue(begin)
    while q.size() > 0:
        now = q.dequeue()
        x = now[0]
        y = now[1]
        vis[x][y] = 2
        if now == [5, 5]:
            print("Yes")
            return
        for i in range(4):
            x = now[0] + xi[i]
            y = now[1] + yi[i]
            if 0 <= x <= 5 and 0 <= y <= 5 and map_[x][y] == 0 and vis[x][
                    y] == 0:
                q.enqueue([x, y])
    print("No")
    return
Exemple #10
0
def simulation(numSeconds, pagesPerMinute):

    labprinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingtimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask():
            #print("cursecond is %d"%currentSecond)
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not labprinter.busy()) and \
            (not printQueue.isEmpty()):
            nexttask = printQueue.dequeue()
            waitingtimes.append( \
                nexttask.waitTime(currentSecond))
            labprinter.startNext(nexttask)
        labprinter.tick()
    averageWait = sum(waitingtimes) / len(waitingtimes)
    print("Avg wait %6.2f secs %3d tasks remaining." %
          (averageWait, printQueue.size()))
 def levelOrder(self):
     q = Queue()
     q.enqueue(self.root)
     while q.size() > 0:
         treeNode = q.dequeue()
         print(treeNode.key)
         if treeNode.leftChild:
             q.enqueue(treeNode.leftChild)
         if treeNode.rightChild:
             q.enqueue(treeNode.rightChild)
Exemple #12
0
            return False  # 洗完需要换车
        else:
            return True


washer = Washer()
car_queue = Queue()  # 洗车排队,只有10个车位
current: Car = None  # 空档状态
wait_time = []
# 模拟两小时
randomor = random.Random()
for second in range(7200):
    if randomor.randrange(
            600) == 0 and car_queue.size() < 20:  # 概率上600秒来一辆车,概率运算一定会一直进行
        new_car = Car()
        new_car.timestamp = second  # 标记开始等待时间
        car_queue.enqueue(new_car)  # 排到队尾

    # 洗车
    # if washer.current_car_time == 0 and not car_queue.isEmpty():  # 无车在洗,队列有车
    #     current = car_queue.dequeue()  # 队尾为下一个车
    if not washer.wash(current):  # 无车在洗
        if not car_queue.isEmpty():  # 有车可换
            current = car_queue.dequeue()
            wait_time.append(second - current.timestamp)  # 存储车辆等待时间
        else:  # 无车可换
            current = None

print('总共洗车:', len(wait_time), '辆,平均等待时间:',
      sum(wait_time) / len(wait_time), ",还剩", car_queue.size(), '辆车没洗')
c = Tree("c")
d = Tree("d")
e = Tree("e")
f = Tree("f")
g = Tree("g")
h = Tree("h")
i = Tree("i")
j = Tree("j")

a.add_left(b)
a.add_right(c)
b.add_left(d)
b.add_right(e)
d.add_right(g)
g.add_left(h)
e.add_left(f)
c.add_left(i)
c.add_right(j)

from pythonds import Queue

q = Queue()
q.enqueue(a)

while not q.isEmpty():
    cur = q.dequeue()
    print(cur.data)
    if cur.left:
        q.enqueue(cur.left)
    if cur.right:
        q.enqueue(cur.right)