def bfs(self, data): ''' This function will help us find an node given our elements are not entirely sorted or our method of sorting the data is not exactly clear (we might have a heap). This function will do a breadth first search which is similar to a level order traversal in that we will search level by level. INPUT: data = Data to be searched for OUTPUT: Node containing the data given the data exists in the tree, otherwise None Runtime -- O(n) -- The runtime is proptional to the amount of data in our BST because we might have to search every node before finding the correct node. Average runtime is O(n). ''' queue = Queue.Queue() queue.enque(self.root) while not queue.isEmpty(): node = queue.deque() if node.getData() == data: return node if node.getLeft(): queue.enque(node.getLeft()) if node.getRight(): queue.enque(node.getRight()) return None
def levelOrderTraversal(self): ''' This function will allow us to do an level order traversal (ie, from left to right, level by level). In other words we follow the traversal of checking the nodes on each level of the tree. Here we finally use the queue class. You can see more here: https://en.wikipedia.org/wiki/Tree_traversal INPUT: None OUTPUT: Level order traversal of our BST. Runtime -- O(n) -- This function runs in O(n) because we have to visit every single node. ''' queue = Queue.Queue() lst = [] queue.enque(self.root) while not queue.isEmpty(): node = queue.deque() lst.append(node) if node.getLeft(): queue.enque(node.getLeft()) if node.getRight(): queue.enque(node.getRight()) return lst
def Get_LevelOrder(self): x = Queue() x.enqueue(self.store) z = [] y = x.dequeue() while (y != False): z += [y[0]] for i in y[1]: x.enqueue(i.store) y = x.dequeue() return z
def BFS(self): if self.root is None: return q = Queue() q.enqueue(self.root) while q.length > 0: curr = q.dequeue() print(curr.data, end=" ") if curr.left is not None: q.enqueue(curr.left) if curr.right is not None: q.enqueue(curr.right) print()
def Hot(name_list, num): q = Queue() if len(name_list) == 0: return None else: for name in name_list: q.enqueue(name) while num >= 1: first = q.dequeue() q.enqueue(first) num -= 1 return q.dequeue()
def __bfs(self, v): ''' Once we initialize everything (set everything to unexplored), we need a queue to help us visit the locations we need. The algorithm looks like this 1. Enqueue the first vertex 2. Report on it 3. While !q.isempty(): 1. Dequeue 2. Report 3. Loop through the adjacent vertices - Update the edges, mark the vertex as visited (if not yet visited); enqueue - If visited, check if edge has been visited, if not mark the edge as a cross edge which means we have a cycle A BFS will give us the shortest path in terms of number of edges. But it has to be from the starting point to a final point cant be two points in between. In addition, the discovery edges that are made by the DFS produce a spanning tree. A cross edge in BFS will only change the distance from the root by a maximum of one. Remember, graph traversals can have any order we want. It all depends on the starting point. Runtime - O(n + m) - This runtime is a little tricky to derive but I will try my best. Since we have to enqueue every single vertex onto the queue at least once, we get O(n). However, since we also have to visit every single adjacent vertex to a given vertex, which is equal to def(v), we get 2m. We get 2m, by summing up all of the degrees of all of the nodes which we visit. This finally gives us a runtime of O(n + 2m) = O(m + n). This is a very good run time because we have to visit every single node and edge in this version of a breadth first search (traversal). ''' queue = Queue.Queue() v.setVisited(True) queue.enque(v) print(v) while not queue.isEmpty(): vert = queue.deque() for adjvert in self.adjacentVertices(vert): edge = self.areAdjacent(adjvert, vert) if not adjvert.getVisited(): print(adjvert) adjvert.setVisited(True) edge.visited = True edge.discovery = True queue.enque(adjvert) elif not edge.visited: self.cycles = True edge.visited = True edge.discovery = False
def main(): graph = [] h = Node("h", []) g = Node("g", []) f = Node("f", []) e = Node("e", [h]) d = Node("d", [e, f, g]) c = Node("c", [d]) b = Node("b", [d]) a = Node("a", [b, c]) graph.extend((a, b, c, d, e, f, g, h)) starting_node = graph[0] q = Queue.Queue() q.offer(starting_node) starting_node.visited = True while q.isEmpty() is not True: node = q.poll() for neighbor in node.neighbors: if neighbor.visited is False: neighbor.visited = True print(neighbor.data) q.offer(neighbor)
def poll(self): if self.isEmpty(): raise Queue.QueueError("Queue is empty!") self.array_list.pop()
def peek(self): if self.isEmpty(): raise Queue.QueueError("Queue is empty!") return self.array_list[self.size() - 1]
# Title: Assignment 8 # Author: Benjamin Lemery # Date: 3/24/20 import time import random from Stack import Stack from Queues import Queue stack = Stack() queue = Queue() starting_balance = 1000 balance = starting_balance current_stock_value = 20 # int(input("Enter the current stock price: $")) accounting_system = int( input('Press 1 if you use FIFO accounting\n' 'Press 2 if you use LIFO account :')) while True: user_selection = int( input("Press 1 to check profit or losses\n" "Press 2 to check running stock\n" "Press 3 to buy stock.\n" "Press 4 to sell stock.")) if user_selection == 1: if balance < starting_balance: print("You have lost: " + str(starting_balance - balance) + '\n' + "Your current balance is: $" + str(balance))
def test_queue(self): q = Queue() self.assertEqual(None, q.peek()) self.assertEqual([], q.to_array()) q.enqueue(1) self.assertEqual([1], q.to_array()) self.assertEqual(1, q.peek()) q.enqueue(2) self.assertEqual([1, 2], q.to_array()) self.assertEqual(1, q.peek()) q.enqueue(3) self.assertEqual([1, 2, 3], q.to_array()) self.assertEqual(1, q.peek()) q.enqueue(4) self.assertEqual([1, 2, 3, 4], q.to_array()) self.assertEqual(1, q.peek()) q.enqueue(5) self.assertEqual([1, 2, 3, 4, 5], q.to_array()) self.assertEqual(1, q.peek()) q.dequeue() self.assertEqual([2, 3, 4, 5], q.to_array()) self.assertEqual(2, q.peek()) q.dequeue() self.assertEqual([3, 4, 5], q.to_array()) self.assertEqual(3, q.peek()) q.dequeue() self.assertEqual([4, 5], q.to_array()) self.assertEqual(4, q.peek()) q.dequeue() self.assertEqual([5], q.to_array()) self.assertEqual(5, q.peek()) q.dequeue() self.assertEqual([], q.to_array()) self.assertEqual(None, q.peek())
from Stack import myStack s = myStack() print(s.isEmpty()) s.push(1) s.push("two") print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) print(s.pop()) print(s.pop()) print(s.pop()) print(s.isEmpty()) print(" ") from Queues import Queue q = Queue() print(q.size()) print(q.isEmpty()) q.enqueue(1) q.enqueue(2) print(q.dequeue()) print(" ") from Deque import myDeque d = myDeque() d.addFront('1') d.addRear('2') print(d.size()) print(d.removeFront() + ' ' + d.removeRear()) print(d.size()) print(d.isEmpty())
def queue_data_init(self): # 厂外等待的车辆队列 {TASK_ID:car} 排队但未叫号 car_queue = dict() # 已经叫号但还未入厂的车辆 car_notice = dict() # 厂内情况 factory = self.factory # 厂内 + 厂外所有车辆的预计结束时间 {TASK_ID:时间} car_predict_end_time = copy.deepcopy( self.factory.car_predict_finish_time) # 厂内 + 厂外各仓库的车辆 {仓库代码:[TASK_ID]} warehouse_car = copy.deepcopy(self.factory.warehouse_car) # 厂内 + 厂外各品种车辆 {品种代码:[TASK_ID]} kind_car = copy.deepcopy(self.factory.kind_car) # 读取数据 data = da.read_queue_car_time(self.__init_time__) data_n = da.read_notice_car_time(self.__init_time__) # 初始化car_queue for i in range(len(data)): car_queue[data.iloc[i, 1]] = Car(data.ix[i].tolist()) for i in range(len(data_n)): car_notice[data_n.iloc[i, 1]] = Car(data_n.ix[i].tolist()) sort_notice = sorted(car_notice.values(), key=lambda x: int(x.queue_num)) for car in sort_notice: # # 判断是否已经达到了今日的计划量 # if self.judge_plan(i): # # 已经达到计划量,预计结束时间为第二天零点+cost # ''' # 实际上线 # car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(str(tool.string_to_datetime( # datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")) + datetime.timedelta(days=1)), i.cost) # ''' # car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(str(tool.string_to_datetime(self.__init_time__) + datetime.timedelta(days=1)), i.cost) # # 没有达到计划量,代表今日可以入厂,判断是否可以直接入厂 # el if len(self.factory.car_predict_finish_time) < self.factory.__factory_max_count__ \ and self.judge_factory_warehouse(car) and self.judge_factory_kind(car): # 此时均未达到厂内最大车辆、该车仓库最大量、该车物料最大量,代表可以直接入厂,等待时间为0 ''' 实际上线 car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(tool.datetime_to_string(datetime.datetime.now()), i.cost) ''' car_predict_end_time[ car.task_id] = tool.cal_predict_finish_time( self.__init_time__, car.cost) # 不可以直接入厂,需要计算等待时间,厂内+厂外考虑 else: # 有相同品种且有相同仓库的,等待时间=仓库最早出来的和品种车辆的最早出来的偏晚的值 if self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time) != '9999-99-99 99:99:99'\ and self.find_kind_early_finish_car(car, kind_car, car_predict_end_time) != '9999-99-99 99:99:99': car_predict_end_time[car.task_id] = tool.cal_predict_finish_time\ (max(self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time), self.find_kind_early_finish_car(car, kind_car, car_predict_end_time)), car.cost) # 只有相同仓库的 elif self.find_warehouse_early_finish_car( car, warehouse_car, car_predict_end_time) != '9999-99-99 99:99:99': car_predict_end_time[car.task_id] = tool.cal_predict_finish_time\ ((self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time)), car.cost) # 只有相同品种的 else: car_predict_end_time[car.task_id] = tool.cal_predict_finish_time\ ((self.find_kind_early_finish_car(car, kind_car, car_predict_end_time)), car.cost) if car.warehouse_code not in warehouse_car.keys(): warehouse_car[car.warehouse_code] = [car.task_id] else: warehouse_car[car.warehouse_code].append(car.task_id) if car.kind_code not in kind_car.keys(): kind_car[car.kind_code] = [car.task_id] else: kind_car[car.kind_code].append(car.task_id) # 让厂外排队车辆根据排队号码排序 sort_queue=[car] sort_queue = sorted(car_queue.values(), key=lambda x: int(x.queue_num)) # 初始化厂外排队车辆的预计结束时间 for car in sort_queue: # # # 判断是否已经达到了今日的计划量 # if self.judge_plan(i): # # 已经达到计划量,预计结束时间为第二天零点+cost # ''' # 实际上线 # car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(str(tool.string_to_datetime( # datetime.datetime.now().strftime("%Y-%m-%d 00:00:00")) + datetime.timedelta(days=1)), i.cost) # ''' # car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(str(tool.string_to_datetime(self.__init_time__) + datetime.timedelta(days=1)), i.cost) # # 没有达到计划量,代表今日可以入厂,判断是否可以直接入厂 # el # if len( self.factory.car_predict_finish_time ) < self.factory.__factory_max_count__ and self.judge_factory_warehouse( car) and self.judge_factory_kind(car): # 此时均未达到厂内最大车辆、该车仓库最大量、该车物料最大量,代表可以直接入厂,等待时间为0 ''' 实际上线 car_predict_end_time[i.task_id] = tool.cal_predict_finish_time(tool.datetime_to_string(datetime.datetime.now()), i.cost) ''' car_predict_end_time[ car.task_id] = tool.cal_predict_finish_time( self.__init_time__, car.cost) # 不可以直接入厂,需要计算等待时间,厂内+厂外考虑 else: # 有相同品种且有相同仓库的,等待时间=仓库最早出来的和品种车辆的最早出来的偏晚的值 if self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time) != '9999-99-99 99:99:99'\ and self.find_kind_early_finish_car(car, kind_car, car_predict_end_time) != '9999-99-99 99:99:99': car_predict_end_time[car.task_id] = tool.cal_predict_finish_time\ (max(self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time), self.find_kind_early_finish_car(car, kind_car, car_predict_end_time)), car.cost) # 只有相同仓库的 elif self.find_warehouse_early_finish_car( car, warehouse_car, car_predict_end_time) != '9999-99-99 99:99:99': car_predict_end_time[car.task_id] = tool.cal_predict_finish_time \ ((self.find_warehouse_early_finish_car(car, warehouse_car, car_predict_end_time)), car.cost) # 只有相同品种的 else: car_predict_end_time[car.task_id] = tool.cal_predict_finish_time \ ((self.find_kind_early_finish_car(car, kind_car, car_predict_end_time)), car.cost) if car.warehouse_code not in warehouse_car.keys(): warehouse_car[car.warehouse_code] = [car.task_id] else: warehouse_car[car.warehouse_code].append(car.task_id) # 初始化kind_car if car.kind_code not in kind_car.keys(): kind_car[car.kind_code] = [car.task_id] else: kind_car[car.kind_code].append(car.task_id) return Queue(car_queue, factory, warehouse_car, kind_car, car_notice, car_predict_end_time)