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 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)
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
def __init__(self, n_balcao, num_bag): """ Inicializa um balcão com o número indicado :param n_balcao: número do balcão :param num_bag: o número máximo de bagagens permitido por passageiro """ self.n_balcao = n_balcao self.fila = Queue() self.inic_atend = 0 self.passt_atend = 0 self.numt_bag = 0 self.tempt_esp = 0 self.bag_utemp = randint(1, num_bag)
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
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")
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')
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
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
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()
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
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()))
class StackQ: q1 = Queue() def __init__(self): print('Stack Q initiated') def push(self, x): self.q1.enqueue(x) 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
# 无车在洗 if car == None: return False # 开始洗车 if self.current_car_time == 0: self.current_car_time = car.wash_time # 洗一秒 self.current_car_time -= 1 if self.current_car_time == 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): # 无车在洗
def __init__(self, bulk_sms_provider): self.bulk_sms_provider = bulk_sms_provider self.msg_queue = Queue()
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)
class Balcao: """ Descreve um balcão e a respectiva fila de passageiros """ def __init__(self, n_balcao, num_bag): """ Inicializa um balcão com o número indicado :param n_balcao: número do balcão :param num_bag: o número máximo de bagagens permitido por passageiro """ self.n_balcao = n_balcao self.fila = Queue() self.inic_atend = 0 self.passt_atend = 0 self.numt_bag = 0 self.tempt_esp = 0 self.bag_utemp = randint(1, num_bag) def obtem_n_balcao(self): """ Devolve o valor de n_balcao :return: n_balcao """ return self.n_balcao def obtem_fila(self): """ Devolve o valor da fila :return: fila """ return self.fila def muda_inic_atend(self, tempo_atendimento): """ Acumula em inic_atend o “valor” do tempo de atendimento do passageiro :param tempo_atendimento: tempo de atendimento :return: None """ self.inic_atend = tempo_atendimento def incr_passt_atend(self): """ Incrementa em 1 o passt_atend - total de passageiros atendidos por este balcão :return: None """ self.passt_atend += 1 def muda_numt_bag(self, passageiro): """ Acumula em numt_bag do balcão, o bag_pass do passageiro quando este termina de ser atendido :param passageiro: passageiro processado :return: None """ self.numt_bag += passageiro.obtem_bag_pass() def muda_tempt_esp(self, tempo_espera): """ Acumula em tempt_esp o “t” tempo de espera do passageiro :param tempo_espera: Tempo de espera :return: None """ self.tempt_esp += tempo_espera def __str__(self): """ Retorna o balcão como uma string legível para o utilizador Output esperado: Quando tem passageiros na fila: Balcão 2 tempo 2 : - [b:4 t:1] [b:2 t:2] - Quando não tem passageiros na fila: Balcão 0 tempo 1 : - :return: string """ # Formata a lista de passageiros consoante as especificações if self.fila.isEmpty(): str_pass = "******" else: passageiros_como_str = [ str(passageiro) for passageiro in self.fila.items ] str_pass = "******".format(" ".join(passageiros_como_str)) return "Balcão {} tempo {} : {}".format(self.obtem_n_balcao(), self.tempt_esp, str_pass)