def __init__(self,g,start): ''' The general algorithm is based on 3 colors white: not visited not processed grey: visited but not processed black: visited and processed The term processed means all adjacent vertices have been visited. hence a black node can't have a white neighbor but can have grey or black neighbors We maintain a queue of nodes to be visited and we run the algo until the queue is empty Then for every neighbor of the currentNode, we check if it is white,set it to gray, increment distance by 1,change neighbor's parent to current node and add neighbor to queue Running time: O(V+E) :param g: Graph :param start: starting node or string :return: None ''' if not isinstance(start,Vertex) or not isinstance(g,Graph): raise Exception("Invalid paramaters") start.setDistance(0) start.setPred(None) self.vertQueue=Queue() self.vertQueue.enqueue(start) while (self.vertQueue.size()>0): currentVert=self.vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor()=='white': nbr.setColor('gray') nbr.setDistance(currentVert.getDistance()+1) nbr.setPred(currentVert) self.vertQueue.enqueue(nbr) currentVert.setColor('black')
class Worker: def __init__(self, workrate): self.work = workrate self.currentTask = None self.timeRemaining = 0 self.taskList = Queue() def tick(self): if self.currentTask != None: self.timeRemaining = self.timeRemaining - 1 if self.timeRemaining <= 0: self.currentTask = None if self.taskList.isEmpty() == False: self.startNext() def busy(self): if self.currentTask != None: return True else: return False def addTask(self, task): self.taskList.push(task) def startNext(self): self.currentTask = self.taskList.pop() self.timeRemaining = newtask.getDifficulty() * 60 / self.work
def __init__(self, n_balcao, bag_utemp): 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 = bag_utemp
def __init__(self,n_balcao,fila,inic_atend,passt_atend,numt_bag,tempt_esp,bag_utemp): self.n_balcao = n_balcao self.fila = Queue() self.inic_atend = inic_atend self.passt_atend = passt_atend self.numt_bag = numt_bag self.tempt_esp = tempt_esp self.bag_utemp = random.randint(1, num_bag) self.namesPass = names.get_full_name()
def hotline(namelist,num): simqueue=Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size()>1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) print(simqueue.dequeue()) return simqueue.dequeue()
def hot(names,num): simque = Queue() for name in names: simque.enqueue(name) while simque.size() > 1: for i in range(num): simque.enqueue(simque,dequeue()) simque.dequeue() return simque.dequeue()
def hotPotato(namelist, num): simqueue = Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size() > 1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue()
def transpose(self): for aVertex in self: aVertex.setColor('white') for key in self.vertices: start = self.vertices[key] break vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() toDel = [] for nbr in currentVert.getConnections(): # here is the key if currentVert.connectedTo[nbr] != -1: nbr.connectedTo[currentVert] = -1 toDel.append(nbr) if nbr.getColor() == 'white': vertQueue.enqueue(nbr) for vertex in toDel: if currentVert.connectedTo[vertex] == 0: del currentVert.connectedTo[vertex] currentVert.setColor('black')
def bfs(self, adj_node): adj_node.color = Color.gray adj_node.parent_node = None adj_node.parent_distance = 0 node_queue = Queue() node_queue.enqueue(adj_node) while node_queue.size() > 0: adj_node = node_queue.dequeue() if self.found: break for node_tup in adj_node.child_nodes: vertex = node_tup[0] assert isinstance(vertex, Node) if vertex.color is Color.white: vertex.color = Color.gray vertex.parent_distance = int(node_tup[1]) vertex.parent_node = adj_node node_queue.enqueue(vertex) if vertex.name.strip().lower() == self.destination: self.found = True self.__searched_list__.append(vertex) break adj_node.color = Color.black
def bfs(g,start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while(vertQueue.size() > 0): currentVert = vertQueue.deque() for nbr in currentVert.getConnections(): if nbr.getColor() =='white': nbr.setColor = 'gray' nbr.setDistance(currentVert.getDistance()+1) nbr.setPred(currentVert) currentVert.enque(nbr) currentVert.setColor ='black'
def isReachable(self,u,v): """ :param u: Key :param v: Key :return: """ vertList=self.getVertices() assert(u in vertList and v in vertList) start=self.getVertex(u) end=self.getVertex(v) start.setDistance(0) start.setPred(None) vertQueue=Queue() vertQueue.enqueue(start) while(vertQueue.size()!=0): currentVert=vertQueue.dequeue() if currentVert.getId()==end.getId(): return True for nbr in currentVert.getConnections(): if nbr.getColor()=="white": nbr.setColor('gray') nbr.setPred(currentVert) nbr.setDistance(currentVert.getDistance()+1) vertQueue.enqueue(nbr) currentVert.setColor('black') return False
def cria_balcoes(num_balcoes): global balcoes #Definição de variáveis globais para serem usadas noutras funções balcoes=[] for i in range(0, num_balcoes, 1): balcao=Balcao(i, Queue(), 1, 0, 0, 0, random.randrange(1, num_bag)) # print('Balcão gerado: {}'.format(balcao)) - Print de Debugging balcoes.append(balcao)
def __init__(self, n_balcao, num_bag): 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, int(num_bag))
def simulation(numSeconds, tasksPerMinute): worker1 = Worker(2) worker2 = Worker(3) worker3 = Worker(4) team = Team(worker1, worker2, worker3) taskQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newTask(): task = Task(currentSecond) taskQueue.enqueue(task) if (not team.allBusy()) and (not taskQueue.isEmpty()): nextTask = taskQueue.dequeue() team.assignTask(nextText()) waitingtimes.append(nexttask.waitTime(currentSecond)) team.assignTask() team.tick() averageWait = sum(waitingtimes) #/len(waitingtimes) print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, taskQueue.size()))
def test(self, wordStart): if self.isNoChain(wordStart): return False start = self.graph.getVertex(wordStart) start.setDistance(0) start.setPred(None) vrtxQueue = Queue() vrtxQueue.enqueue(start) #print(wordStart,end='') d = defaultdict(list) while vrtxQueue.size() > 0: ls = [] current = vrtxQueue.dequeue() #print(current.getId(),end='') prev = None for neighbour in current.getConnections(): if neighbour.getColor() == "white": neighbour.setColor("gray") neighbour.setDistance(current.getDistance() + 1) neighbour.setPred(current) dist = neighbour.getDistance() word = neighbour.getId() d[dist].append(word) #print("->"+neighbour.getId(),end='') ls.append(neighbour) ##if neighbour.getId() == wordEnd : # print("\n\n\t",end=''); #vrtxQueue.enqueue(neighbour) for i in range(len(ls)): vrtxQueue.enqueue(ls.pop(0)) current.setColor("black") outfile = open('Chains.txt', 'a') print("WORD : " + wordStart, file=outfile) for length in d.keys(): print( '----------------------- Length : {} -----------------------'. format(length), file=outfile) self.frequency.setdefault(length, 0) self.frequency[length] += len(d[length]) for word in d[length]: vert = self.graph.getVertex(word) print(vert.getId(), end='', file=outfile) for count in range(length): print(" -> " + vert.getPred().getId(), end='', file=outfile) #print() vert = vert.getPred() print(file=outfile) print(file=outfile)
def bfs(g,start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr)
def preExpre(aStr): operatorStack = Stack() operandStack = Queue() prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 1 prec["("] = 0 tokenStr = aStr.split() preExpressen = []
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == "while": nbr.setColor("gray") nbr.setDistance(currentVert.getDistance + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor("black")
def bfs(g, start): # --起始顶点作为参数 start.setDistance(0) # --起始顶点的距离 start.setPred(None) # --前驱 vertQueue = Queue() vertQueue.enqueue(start) # --加入到队列里 while (vertQueue.size() > 0): # --只要队列有顶点 currentVert = vertQueue.dequeue() # -- 取队首作为当前顶点 for nbr in currentVert.getConnections(): # --遍历邻接顶点 if (nbr.getColor() == 'white'): # --邻接顶点是白色的 nbr.setColor('gray') # --将邻接顶点改为灰色 nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) # --前驱设为当前顶点 vertQueue.enqueue(nbr) # --入队,排到队尾 currentVert.setColor('black') # --for循环结束,将当前顶点设为黑色
def pathExists(start,end): vertexQueue=Queue() vertexQueue.enqueue(start) while (vertexQueue.size()>0): item=vertexQueue.dequeue() if item.getId()==end.getId(): print ("path exists") return True else: for vertex in item.getConnections(): if vertex.getColor()=="white": vertex.setColor("gray") vertexQueue.enqueue(vertex) return False
def breadthFirstSearch(start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: dequeueVert = vertQueue.dequeue() for neighbor in dequeueVert.getConnections(): if neighbor.getColor() == 'white': vertQueue.enqueue(neighbor) neighbor.setColor('gray') neighbor.setDistance(dequeueVert.getDistance() + 1) neighbor.setPred(dequeueVert) dequeueVert.setColor('black')
def bfs(g, start): start.setDistance(0) #起点的距离设为0 start.setPred(None) #起点没有父节点 vertQueue = Queue() #建立一个队列 vertQueue.enqueue(start) #将起点加入队列中 while (vertQueue.size() > 0): #当队列存在对象时 currentVert = vertQueue.dequeue() #弹出对象并设置为当前节点 """该迭代阐明了bfs的特点就是把每个邻居都遍历,先完成一层,再往下完成,“广”""" for nbr in currentVert.getConnections(): #搜索当前节点的所有邻居 if (nbr.getColor() == 'white'): #如果邻居x是白色的(即待搜索) nbr.setColor('gray') #设为灰色意为正在处理 nbr.setDistance(currentVert.getDistance() + 1) #该邻居距离为当前节点+1 nbr.setPred(currentVert) #该邻居的父节点是当前节点 vertQueue.enqueue(nbr) #队列加入该邻居
def simulateOneServer(file_name): import pandas as pd df = pd.read_csv(file_name, index_col=0, names = ['currentSecond', 'task', 'Time']) df2 = df.reset_index() server = Server() requestQueue = Queue() waitingtimes = [] starttime = df2['currentSecond'][0] for x in range(len(df2)): task = Task(df2['Time'][x]) requestQueue.enqueue(task) for x in range(len(df2)): endtime = starttime + df2['Time'][x] starttime = endtime nexttask = requestQueue.dequeue() waitingtimes.append(nexttask.waitTime(starttime, df2['currentSecond'][x])) if (not server.busy()) and (not requestQueue.isEmpty()): server.startNext(nexttask) server.tick() averageWait=sum(waitingtimes)/len(waitingtimes) print("Average Wait %6.2f secs for a single server."%(averageWait))
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black') print(currentVert) # prints the status of the current visited vertex
def bfs(graph, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() # 利用队列储存邻接的顶点 vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() # 对出列的顶点进行操作 for nbr in currentVert.getConnections(): if nbr.getColor( ) == 'white': # 这是pythonds中写好的初始化属性,为白色,代表了此顶点未被探索过 nbr.setColor('gray') # 一个顶点第一次被发现,则被标记为灰色 nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black') # 一个顶点的所有邻接顶点都被探索后会被标记为黑色
def bfs(self, start): # start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): # print(nbr) if nbr.getColor() == 'white': nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black')
def bfs(g, start, searchKey): vertexQueue = Queue() start.setDistance(0) vertexQueue.enqueue(start) while (vertexQueue.size() > 0): currentVertex = vertexQueue.dequeue() print currentVertex.getId() if (searchKey == currentVertex.getId()): print "distance is", currentVertex.getDistance() break for vertex in currentVertex.getConnections(): if (vertex.getColor() == "white"): vertex.setColor("gray") print currentVertex.getDistance() vertex.setDistance(currentVertex.getDistance() + 1) vertexQueue.enqueue(vertex) currentVertex.setColor("black")
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == "white": nbr.setColor("gray") nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor("black")
def bfs(g,start): start.setDistance(0) start.setPred(None)#set predecessor to none in order to make this the root of the tree vertQueue = Queue() #instantiates a queque vertQueue.enqueue(start) #adds to queque while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() #removes first vertex added to the queque for nbr in currentVert.getConnections(): #gets the vertex's list of connections and loops through the list if (nbr.getColor() == 'white'):#if unexplored nbr.setColor('gray')#set to explored nbr.setDistance(currentVert.getDistance() + 1) #Gives weight/distance of vertex to root. Can be considered layers of tree nbr.setPred(currentVert)#set predecessor/parent vertex vertQueue.enqueue(nbr) #places back in queue to explore if vertex has other connections/children currentVert.setColor('black') #explored
class Balcao: def __init__(self,n_balcao,fila,inic_atend,passt_atend,numt_bag,tempt_esp,bag_utemp): self.n_balcao = n_balcao self.fila = Queue() self.inic_atend = inic_atend self.passt_atend = passt_atend self.numt_bag = numt_bag self.tempt_esp = tempt_esp self.bag_utemp = random.randint(1, num_bag) self.namesPass = names.get_full_name() def __str__(self): # Apresenta em lista os atributos e respetivos valores do balcão return "Balcão Nº: " + str(self.n_balcao) + \ "\n" + "Tamanho da fila de espera: " + str(self.obtem_tam_fila()) + \ "\n" + "Passageiros em fila: " + str(self.obtem_pass_fila()) + \ "\n" + "inic_atend: " + str(self.inic_atend) + \ "\n" + "passt_atend: " + str(self.passt_atend) + \ "\n" + "numt_bag: " + str(self.numt_bag) + \ "\n" + "tempt_esp: " + str(self.tempt_esp) + \ "\n" + "bag_utemp: " + str(self.bag_utemp) + "\n" def muda_inic_atend(self, tempAtend): self.inic_atend = tempAtend def incr_passt_atend(self): self.passt_atend += 1 def muda_numt_bag(): pass def muda_tempt_esp(tempEspera): self.tempt_esp += tempEspera # função para devolver os passageiros da fila def obtem_pass_fila(self): return self.fila.items # função para devolver o tamanho da fila def obtem_tam_fila(self): return self.fila.size() def obtem_balcao(self): return self.n_balcao def obtem_inic_atend(self): return self.inic_atend def obtem_passst_atend(self): return self.passt_atend def obtem_numt_bag(self): return self.numt_bag def obtem_tempt_esp(self): return self.tempt_esp def obtem_bag_utem(self): return self.bag_utemp
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while vertQueue.size() > 0: currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if nbr.getColor() == 'white': # gray means in queue, waiting to be exhausted nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) # black means it's exhausted currentVert.setColor('black')
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) # insert(0) # 直接用list也行 # 循环时(只要Queue不为空)首先从Queue队尾dequeue出点v # 找v的邻接点然后enqueue进入队首 # 将v置为black while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() # pop() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black')
class Balcao: def __init__(self, n_balcao, bag_utemp): 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 = bag_utemp def __str__(self): return '[b:' + str(self.n_balcao) + ' t:' + str(self.inic_atend) + ' fila:' + str(self.fila.size()) + ']' def muda_inic_atend(self, tempoatendimento): self.inic_atend += tempoatendimento def incr_passt_atend(self): self.passt_atend += 1 def muda_numt_bag(self, bagpass): self.numt_bag += bagpass def muda_tempt_esp(self, t): self.tempt_esp += t def obtem_n_balcao(self): return self.n_balcao def obtem_fila(self): return self.fila def obtem_inic_atend(self): return self.inic_atend def obtem_passt_atend(self): return self.passt_atend def obtem_numt_bag(self): return self.numt_bag def obtem_tempt_esp(self): return self.tempt_esp def obtem_bag_utemp(self): return self.bag_utemp
def simulation(numSeconds, itemsPerMinute): ourClerk = Clerk(itemsPerMinute) clerkQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newCustomer(): customer = Customer(currentSecond) clerkQueue.enqueue(customer) if (not ourClerk.busy()) and (not clerkQueue.isEmpty()): nextCustomer = clerkQueue.dequeue() waitingtimes.append(nextCustomer.waitTime(currentSecond)) ourClerk.startNext(nextCustomer) ourClerk.tick() averageWait = sum(waitingtimes)/len(waitingtimes) print('Average Wait %6.2f secs %3d tasks remaining.'%(averageWait, clerkQueue.size()))
def bfs(g,start,searchKey): vertexQueue=Queue() start.setDistance(0) vertexQueue.enqueue(start) while (vertexQueue.size()>0): currentVertex=vertexQueue.dequeue() print currentVertex.getId() if(searchKey==currentVertex.getId()): print "distance is",currentVertex.getDistance() break for vertex in currentVertex.getConnections(): if (vertex.getColor()=="white"): vertex.setColor("gray") print currentVertex.getDistance() vertex.setDistance(currentVertex.getDistance()+1) vertexQueue.enqueue(vertex) currentVertex.setColor("black")
def bfs(g,s): #s = g.getVertex(vertKey) s.setDistance(0) s.setPred(None) s.setColor('gray') Q = Queue() Q.enqueue(s) while (Q.size() > 0): w = Q.dequeue() for v in w.getAdj(): print v.id if(v.getColor() == 'white'): v.setColor('gray') v.setDistance(w.getDistance() + 1) v.setPred(w) Q.enqueue(v) w.setColor('black')
def bfs(g, start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): current_vertex = vertQueue.dequeue() for nbr in current_vertex: if nbr.getColor() == 'white': nbr.setColor('gray') nbr.setDistance(current_vertex.getDistance() + 1) nbr.setPred(current_vertex) vertQueue.enqueue(nbr) current_vertex.setColor('black')
def bfs(seed, graph): """ Finds connected nodes to seeds with given graph Args: seed (Vertex): vertex with seed ID graph (Graph): contains edges from source node to target node Returns: list(str(seed ID)): list of connected seeds """ seed.setDistance(0) seed.setPred(None) vertQueue = Queue() vertQueue.enqueue(seed) connected_nodes = [] while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance()+1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) connected_nodes.append(nbr.getId()) currentVert.setColor('black') return connected_nodes
def simulation(numSeconds, pagesPerMinute): labprinter = Printer(pagesPerMinute) printQueue = Queue() waitingtimes = [] for currentSecond in range(numSeconds): if newPrintTask(): 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("Average Wait %6.2f secs %3d tasks remaining."\ %(averageWait,printQueue.size()))