def __init__(self): self.lifo = LifoQueue()
def solve_puzzle(self): global current_node current_node = tuple(self.puzzle) number_of_puzzle_elements = len(self.puzzle) frontier = LifoQueue(maxsize=self.max_recursion_depth + 1) frontier.put(tuple(self.puzzle)) path = '' visited_nodes = set(tuple(self.puzzle)) sorted_puzzle = self.sort_puzzle(number_of_puzzle_elements) max_recursion_depth = 0 current_recursion_depth = 0 start_time = time.time() * 1000 is_game_solved = self.visit_node(self.puzzle, sorted_puzzle) if is_game_solved: frontier.get() i = 0 while not is_game_solved: if i >= len(self.strategy_param) or frontier.full(): frontier.get() path = path[:-1] i = 0 current_node = frontier.get() frontier.put(current_node) current_recursion_depth -= 1 next_node = self.check_possible_moves(self.strategy_param[i], list(current_node[:])) if next_node is None or next_node in visited_nodes: i += 1 else: path += self.strategy_param[i] i = 0 current_node = next_node frontier.put(current_node) current_recursion_depth += 1 if current_recursion_depth > max_recursion_depth: max_recursion_depth = current_recursion_depth is_game_solved = self.visit_node(current_node, sorted_puzzle) visited_nodes.add(current_node) if frontier.qsize() == 1 and i >= len(self.strategy_param): is_game_solved = True end_time = time.time() * 1000 if frontier.qsize() == 1 and i >= len(self.strategy_param): self.solution_length = -1 else: self.solution_time = round((end_time - start_time), 3) self.solution_path = path self.solution_length = len(self.solution_path) self.number_of_visited_nodes = visited_nodes.__len__( ) + frontier.qsize() self.number_of_processed_nodes = visited_nodes.__len__() self.recursion_depth = max_recursion_depth
def __setstate__(self, state): # Restore the session pool and lock self.__dict__.update(state) self._session_pool = LifoQueue() self._session_pool_lock = Lock()
def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) container = Frame(self) container.grid() self.serial = SerialComm() self.frames = {} self.q = LifoQueue() self.eye_tracker = EyeTracker(self.q) self.variables = {} self.fps = IntVar() self.fps.set(20) self.temp = IntVar() self.temp.set(20) self.temp.trace("w", self.send_command) self.variables[self.temp.__str__()] = 't', self.temp self.temp_current = StringVar() self.temp_current.set('Temperature') self.tts = StringVar() self.tts.set('Type and Play') self.temp_offset = IntVar() self.temp_offset.set(5) self.temp_offset.trace("w", self.send_command) self.variables[self.temp_offset.__str__()] = 'o', self.temp_offset self.samples = 9 self.window = IntVar() self.window.trace("w", self.send_command) self.variables[self.window.__str__()] = 'w', self.window self.mouse_control = BooleanVar() self.mouse_control.set(False) self.talk = BooleanVar() self.talk.set(True) self.alarm = BooleanVar() self.alarm.set(False) self.alarm.trace("w", self.send_command) self.variables[self.alarm.__str__()] = 'a', self.alarm self.light = BooleanVar() self.light.set(False) self.light.trace("w", self.send_command) self.variables[self.light.__str__()] = 'l', self.light self.heater = BooleanVar() self.heater.set(False) self.heater.trace("w", self.send_command) self.variables[self.heater.__str__()] = 'h', self.heater self.ac = BooleanVar() self.ac.set(False) self.ac.trace("w", self.send_command) self.variables[self.ac.__str__()] = 'f', self.ac self.move = BooleanVar() self.move.set(False) self.w, self.h = pyautogui.size() self.hor_div = DoubleVar() self.hor_div.set(5) self.hor_div.trace("w", self.send_command) self.variables[self.hor_div.__str__()] = 'hor', self.hor_div self.ver_div = DoubleVar() self.ver_div.set(5) self.ver_div.trace("w", self.send_command) self.variables[self.ver_div.__str__()] = 'ver', self.ver_div self.mouse_directions = [] self.mouse = MouseAndSpeech(self) self.t = Thread(target=self.mouse.process) self.t.start() self.frame = None self.draw = False frame = Preview(container, self) self.frames[Preview] = frame frame.grid(row=0, column=1, sticky="nsew", rowspan=100) self.current_frame = frame frame = Settings(container, self) self.frames[Settings] = frame frame.grid(row=0, column=0, sticky="nsew", pady=10, padx=10) frame.grid_remove() frame = Applications(container, self) self.frames[Applications] = frame frame.grid(row=0, column=0, sticky="nsew", pady=10, padx=10) frame.grid_remove() # Menu Bar menu = MyMenu(self) self.config(menu=menu) Tk.iconbitmap(self, default=resource_path('icon.ico')) Tk.wm_title(self, "Senior") w = (self.winfo_screenwidth() - self.eye_tracker.window_size) // 2 self.geometry('+{}+{}'.format(w, 0)) self.protocol("WM_DELETE_WINDOW", lambda: self.close())
def branch_and_bound(items, capacity): sorted_items = sorted(items, key=lambda item: -item.value) items = sorted(sorted_items, key=lambda item: -item.value / item.weight) def calculate_max_profit(cur_value, capacity, index): # print(cur_value, capacity) cur_items = items[index:] # print(cur_items) remaining_capacity = capacity i = 0 for item in cur_items: # print(item, remaining_capacity, cur_value) if item.weight <= remaining_capacity: i += 1 cur_value += item.value remaining_capacity -= item.weight else: break if (i + index) != len(items): # print('<<<<<<<<', item, cur_value, remaining_capacity) # print(cur_value, remaining_capacity, item) cur_value += item.value * remaining_capacity / float(item.weight) # print(cur_value, remaining_capacity) return cur_value max_value = 0 max_taken = None taken_root = [0] * len(items) queue = LifoQueue() queue.put((0, capacity, 0, taken_root)) while not queue.empty(): cur_value, cur_capacity, index, taken = queue.get() if cur_capacity < 0: continue if cur_value > max_value: max_value = cur_value max_taken = taken if cur_capacity <= 0 or index >= len(items): continue # print('>>>', cur_value, cur_capacity) cur_max_profit = calculate_max_profit(cur_value, cur_capacity, index) # print(cur_value, cur_capacity, index, cur_max_profit, max_value) # print(cur_max_profit) if cur_max_profit < max_value: continue queue.put((cur_value, cur_capacity, index + 1, taken)) include_taken = taken[:] include_taken[items[index].index] = 1 queue.put( (cur_value + items[index].value, cur_capacity - items[index].weight, index + 1, include_taken)) return max_value, max_taken
def stack2(): stack = LifoQueue() stack.put(0) stack.put(1) stack.put(2) stack.get()
try: second_run = open('run2.txt') print("Data from run two found, calculating faster route") this_run = 3 except: pass except: # we don't actually care if a file isn't found, since that probably just means this is a new run pass # get the time step of the current world. (physics frames) timestep = 64 path_stack = LifoQueue() ps=[] psNames = [ 'ps0', 'ps1', 'ps2', 'ps3', 'ps4', 'ps5', 'ps6', 'ps7' ] for i in range(8): ps.append(robot.getDistanceSensor(psNames[i])) ps[i].enable(timestep) left_motor = robot.getMotor('left wheel motor') right_motor = robot.getMotor('right wheel motor') left_motor.setPosition(float('inf')) right_motor.setPosition(float('inf')) left_motor.setVelocity(0.0)
from queue import Queue, LifoQueue, PriorityQueue METHODS = { 'breadth': Queue(), # Queue Data Structure for breadth first search 'depth': LifoQueue(), # Stack Data Structure for depth first search 'astar': PriorityQueue(), # Priority Queue for astar search 'best': PriorityQueue() # Priority Queue for best search } # Loads the problem from .txt file and stores it into an array. def loadProblem(fileName): with open(fileName, "r") as file: data = file.readlines() new_data = [item.replace('\n', '') for item in data] return new_data # Initializes the initial problem of the game def initializeProblem(data): # The game of the problem will game = {} # Pass the data of the initial read that we got to the stacks of the problem, where each one of them has an id from 1 to 8 game["stack"] = {} i = 1 for line in data: formattedData = line.split(' ') game["stack"][i] = formattedData i = i + 1
def _create_session_pool(self): # Create a pool to reuse sessions containing connections to the server session_pool = LifoQueue(maxsize=self._session_pool_size) for _ in range(self._session_pool_size): session_pool.put(self.create_session(), block=False) return session_pool
def connect(self): """ This function will open the port immediately. Function will wait for the READY Message for 5 secs. | Once received READY message, will finish connection. """ if self.port_name is None and self.ble == False: ports = uarm_ports() if len(ports) > 0: self.port_name = ports[0] else: raise UArmConnectException(3) self.__data_buf = [] self.__position_queue = LifoQueue() self.__menu_button_queue = LifoQueue() self.__play_button_queue = LifoQueue() self.__send_queue = Queue() self.__firmware_version = None self.__hardware_version = None self.__isReady = False self.serial_id = 1 if self.ble == False: self.port = get_port_property(self.port_name) self.__receive_thread = threading.Thread( target=self.__receive_thread_process) self.__send_thread = threading.Thread( target=self.__send_thread_process) self.__receive_thread.setDaemon(True) self.__send_thread.setDaemon(True) self.msg_buff = {} self.__serial = serial.Serial(baudrate=115200, timeout=0.1) try: self.__serial.port = self.port.device printf("Connecting from port - {0}...".format( self.port.device)) self.__serial.open() self.__init_serial_core() self.__connect() except serial.SerialException as e: raise UArmConnectException( 0, "port: {}, Error: {}".format(self.port.device, e.strerror)) else: # set up the characteristic to write to the ble module at self.mac_address if self.mac_address is None: raise (ValueError( "Scanning for peripherals is not yet implemented, please specify a mac address. --Matt." )) try: print("Connecting to BLE") self.ble_delegate = ble_delegate = UArmDelegate() self.peripheral = peripheral = Peripheral( self.mac_address).withDelegate(ble_delegate) tries = 0 while self.peripheral.getState() != 'conn': self.peripheral.connect() tries += 1 if tries > 5: raise (f"Could not connect to {self.mac_address}" ) # and hit an exception below self.services = services = list(peripheral.getServices()) self.ble_channel = services[-1].getCharacteristics( )[0] # hm-10 uses a custom characteristic on the third service to communicate # self.connection_state = True # this is a dumb hack, but I'm not sure how to query if connected with bluepy except Exception as e: raise UArmConnectException(0, str(e))
from queue import LifoQueue t = int(input()) for i in range(t): n = int(input()) l = list(map(int, input().split())) s = LifoQueue(maxsize=n) p = [] for j in range((len(l) - 1), -1, -1): if s.empty(): p.append(-1) elif s.qsize() > 0 and s.queue[-1] < l[j]: p.append(s.queue[-1]) elif s.qsize() > 0 and s.queue[-1] >= l[j]: while (s.qsize() > 0 and s.queue[-1] >= l[j]): s.get() if s.empty(): p.append(-1) else: p.append(s.queue[-1]) s.put(l[j]) p = p[::-1] print(*p)
print(row_format.format(str(l), str(r)),file=fp) args = get_args() initial_state = read_from_file(args.initial_state) goal_state = read_from_file(args.goal_state) #using python queue classes for consistency in gsearch algorithm :) #docs for these data structs: https://docs.python.org/3/library/queue.html if(args.mode == "bfs"): frontier = Queue() elif(args.mode == "astar"): frontier = PriorityQueue() elif (args.mode.find("dfs") != -1): #dfs or iddfs frontier = LifoQueue() else: #print("need to add frontier data structure for Astar :)") exit() if args.mode == "iddfs": for x in range(750): #unsure what to set this to. it works, but it could probably be smaller :) cost, count, path = graph_search(frontier, initial_state, goal_state, x) if cost != -1: break elif args.mode == "astar": cost, count, path = astar(frontier, initial_state, goal_state) else: cost, count, path = graph_search(frontier, initial_state, goal_state) with open(args.output_filename, "w") as fp:
def build(cls, name, _async, requests, args=None, backend=None, id=None, procedure_class=None, **kwargs): reqs = [] for_count = 0 while_count = 0 if_count = 0 if_config = LifoQueue() procedure_class = procedure_class or cls key = None for request_config in requests: # Check if it's a break/continue/return statement if isinstance(request_config, str): reqs.append(Statement(request_config)) continue # Check if this request is an if-else if len(request_config.keys()) >= 1: key = list(request_config.keys())[0] m = re.match('\s*(if)\s+\${(.*)}\s*', key) if m: if_count += 1 if_name = '{}__if_{}'.format(name, if_count) condition = m.group(2) if_config.put({ 'name': if_name, '_async': False, 'requests': request_config[key], 'condition': condition, 'else_branch': [], 'backend': backend, 'id': id, }) continue if key == 'else': if if_config.empty(): raise RuntimeError('else statement with no ' + 'associated if in {}'.format(name)) conf = if_config.get() conf['else_branch'] = request_config[key] if_config.put(conf) if not if_config.empty(): reqs.append(IfProcedure.build(**(if_config.get()))) if key == 'else': continue # Check if this request is a for loop if len(request_config.keys()) == 1: key = list(request_config.keys())[0] m = re.match('\s*(fork?)\s+([\w\d_]+)\s+in\s+(.*)\s*', key) if m: for_count += 1 loop_name = '{}__for_{}'.format(name, for_count) # A 'for' loop is synchronous. Declare a 'fork' loop if you # want to process the elements in the iterable in parallel _async = True if m.group(1) == 'fork' else False iterator_name = m.group(2) iterable = m.group(3) loop = ForProcedure.build(name=loop_name, _async=_async, requests=request_config[key], backend=backend, id=id, iterator_name=iterator_name, iterable=iterable) reqs.append(loop) continue # Check if this request is a while loop if len(request_config.keys()) == 1: key = list(request_config.keys())[0] m = re.match('\s*while\s+\${(.*)}\s*', key) if m: while_count += 1 loop_name = '{}__while_{}'.format(name, while_count) condition = m.group(1).strip() loop = WhileProcedure.build(name=loop_name, _async=False, requests=request_config[key], condition=condition, backend=backend, id=id) reqs.append(loop) continue request_config['origin'] = Config.get('device_id') request_config['id'] = id if 'target' not in request_config: request_config['target'] = request_config['origin'] request = Request.build(request_config) reqs.append(request) while not if_config.empty(): pending_if = if_config.get() reqs.append(IfProcedure.build(**pending_if)) return procedure_class(name=name, _async=_async, requests=reqs, args=args, backend=backend, **kwargs)
######################################################################################################################## if len(sys.argv) == 1: start_state = {'state': '275318406', 'moves': ''} init_queue = Queue() init_queue.put(start_state) seen_set = {start_state['state']} t0 = datetime.datetime.now() bfs(init_queue, seen_set) t1 = datetime.datetime.now() print('BFS in', (t1 - t0).total_seconds(), 'seconds') init_stack = LifoQueue() init_stack.put(start_state) seen_set = {start_state['state']} t0 = datetime.datetime.now() result = dfs(init_stack, seen_set) t1 = datetime.datetime.now() print('DFS in', (t1 - t0).total_seconds(), 'seconds') print('max_depth:', result[0]) print('final_stack_size:', result[1]) print('max_seen_size:', result[2]) print('resource.ru_maxrss (KB):', result[3]) init_pq = PriorityQueue() score = heuristic(start_state['state']) init_pq.put((score, start_state['state'], start_state['moves'])) seen_set = {start_state['state']}
def __init__(self): self.nodes = LifoQueue()
def generate_random_maze(width): height = int(width) maze = Image.new('RGB', (2 * width + 1, 2 * height + 1), 'black') pixels = maze.load() # Create a path on the very top and bottom so that it has an entrance/exit pixels[1, 0] = (255, 255, 255) pixels[-2, -1] = (255, 255, 255) stack = LifoQueue() cells = np.zeros((width, height)) cells[0, 0] = 1 stack.put((0, 0)) while not stack.empty(): x, y = stack.get() adjacents = [] if x > 0 and cells[x - 1, y] == 0: adjacents.append((x - 1, y)) if x < width - 1 and cells[x + 1, y] == 0: adjacents.append((x + 1, y)) if y > 0 and cells[x, y - 1] == 0: adjacents.append((x, y - 1)) if y < height - 1 and cells[x, y + 1] == 0: adjacents.append((x, y + 1)) if adjacents: stack.put((x, y)) neighbour = choice(adjacents) neighbour_on_img = (neighbour[0] * 2 + 1, neighbour[1] * 2 + 1) current_on_img = (x * 2 + 1, y * 2 + 1) wall_to_remove = (neighbour[0] + x + 1, neighbour[1] + y + 1) pixels[neighbour_on_img] = (255, 255, 255) pixels[current_on_img] = (255, 255, 255) pixels[wall_to_remove] = (255, 255, 255) cells[neighbour] = 1 stack.put(neighbour) pix = np.array(maze) maze_matrix = [] for row in pix: maz_row = [] for pixel in row: if pixel[0] == 255: maz_row.append(0) else: maz_row.append(1) maze_matrix.append(maz_row) image = maze.resize((400, 400), Image.NEAREST) maze_height = len(maze_matrix) maze_width = len(maze_matrix[0]) grid = [[0 for x in range(maze_width)] for x in range(maze_height)] return maze_matrix, image, grid
def pnl_lifo(self): """ 使用后进先出法配对成交记录 """ X = dict( zip( self.target.code, [{'buy': LifoQueue(), 'sell': LifoQueue()} for i in range(len(self.target.code))] ) ) pair_table = [] for _, data in self.target.history_table_min.iterrows(): while True: if data.direction in[1, 2, -2]: if data.direction in [1, 2]: X[data.code]['buy'].append( (data.datetime, data.amount, data.price, data.direction) ) elif data.direction in [-2]: X[data.code]['sell'].append( (data.datetime, data.amount, data.price, data.direction) ) break elif data.direction in[-1, 3, -3]: rawoffset = 'buy' if data.direction in [-1, -3] else 'sell' l = X[data.code][rawoffset].get() if abs(l[1]) > abs(data.amount): """ if raw> new_close: """ temp = (l[0], l[1] + data.amount, l[2]) X[data.code][rawoffset].put_nowait(temp) if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2], rawoffset ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price, rawoffset ] ) break elif abs(l[1]) < abs(data.amount): data.amount = data.amount + l[1] if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], l[1], data.price, l[2], rawoffset ] ) else: pair_table.append( [ data.code, l[0], data.datetime, l[1], l[2], data.price, rawoffset ] ) else: if data.amount < 0: pair_table.append( [ data.code, data.datetime, l[0], abs(data.amount), data.price, l[2], rawoffset ] ) break else: pair_table.append( [ data.code, l[0], data.datetime, abs(data.amount), l[2], data.price, rawoffset ] ) break pair_title = [ 'code', 'sell_date', 'buy_date', 'amount', 'sell_price', 'buy_price', 'rawdirection' ] pnl = pd.DataFrame(pair_table, columns=pair_title) pnl = pnl.assign( unit=pnl.code.apply(lambda x: self.market_preset.get_unit(x)), pnl_ratio=(pnl.sell_price / pnl.buy_price) - 1, sell_date=pd.to_datetime(pnl.sell_date), buy_date=pd.to_datetime(pnl.buy_date) ) pnl = pnl.assign( pnl_money=(pnl.sell_price - pnl.buy_price) * pnl.amount * pnl.unit, hold_gap=abs(pnl.sell_date - pnl.buy_date), if_buyopen=pnl.rawdirection == 'buy' ) pnl = pnl.assign( openprice=pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_price, opendate=pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.sell_date.map(str), closeprice=pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.buy_price + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_price, closedate=pnl.if_buyopen.apply(lambda pnl: 0 if pnl else 1) * pnl.buy_date.map(str) + pnl.if_buyopen.apply(lambda pnl: 1 if pnl else 0) * pnl.sell_date.map(str) ) return pnl.set_index('code')
""" Implementation of stack in python using LifoQueue """ from queue import LifoQueue stack = LifoQueue(maxsize=4) #PUSH operation is done using put() method for queue stack.put(4) stack.put(5) stack.put(6) stack.put(7) if stack.full(): print("Stack is full") print("SIZE:", stack.qsize()) #POP operation using get() in LIFO order for i in range(stack.qsize()): print("Popped item is:", stack.get()) if stack.empty(): print("Stack is empty")
list_stack.append('c') print(list_stack.pop()) print(list_stack.pop()) print(list_stack.pop()) # deque stack - built upon double linked list - indexing is slower, but adding and removing is fatser # other methods in deque are not thread-safe deque_stack = [] deque_stack.append('a') deque_stack.append('b') deque_stack.append('c') print(deque_stack.pop()) print(deque_stack.pop()) print(deque_stack.pop()) # popleft() for queue # write dequeue to remove something from queue # write enqueue to add something to queue # write push to add something to stack # write pop to remove something from stack # lifoqueue - good for multi-thread # thread-safe, but takes longer than deque q_stack = LifoQueue() q_stack.put('a') q_stack.put('b') q_stack.put('c') print(q_stack.get()) print(q_stack.get()) print(q_stack.get())
def __init__(self): ''' stack implementation using queue module ''' self.stack = LifoQueue(maxsize=100)
def _create_seed_set(self): self._queue = LifoQueue() start_node = random.choice(range(self._graph.number_of_nodes())) self._queue.put(start_node) self._nodes = set() self._path = []
def __init__(self): self.to_crawl = LifoQueue() if self.depth_first else Queue() self.crawled = set()
from queue import LifoQueue stack = LifoQueue(maxsize=3) # Initializing a stack print(stack.qsize() ) # qsize() show the number of elements in the stack # Output: 0 # put() function to push element in the stack stack.put('a') stack.put('b') stack.put('c') print("Full: ", stack.full()) # Full: True print("Size: ", stack.qsize()) # Size: 3 # get() fucntion to pop element from stack in LIFO order print('\nElements poped from the stack') # c b a print(stack.get()) print(stack.get()) print(stack.get()) print("\nEmpty: ", stack.empty()) # Empty: True
def dfs(self, puzzle: Puzzle8): queue_tree = LifoQueue() stack = LifoQueue() return help_search(stack, puzzle, queue_tree)
from queue import LifoQueue q = LifoQueue() for i in range(5): q.put(i) while not q.empty(): print(q.get())
def __init__(self, executor, max_workers=None): self.executor = executor self.max_workers = max_workers or executor._max_workers self.queue = LifoQueue() self.loop = asyncio.get_event_loop() self.sem = asyncio.Semaphore(self.max_workers)
def __init__(self): """ Initialize your data structure here. """ self.in_stack = LifoQueue() self.out_stack = LifoQueue()
@Date: 2020-05-27 22:20:22 @LastEditors: steven @LastEditTime: 2020-06-09 00:54:32 @Description:LILO队列 ''' from queue import Queue #LILO队列 q = Queue() #创建队列对象 q.put(0) #在队列尾部插入元素 q.put(1) q.put(2) print('LILO队列', q.queue) #查看队列中的所有元素 print(q.get()) #返回并删除队列头部元素 print(q.queue) from queue import LifoQueue #LIFO队列 lifoQueue = LifoQueue() lifoQueue.put(1) lifoQueue.put(2) lifoQueue.put(3) print('LIFO队列', lifoQueue.queue) lifoQueue.get() #返回并删除队列尾部元素 lifoQueue.get() print(lifoQueue.queue) from queue import PriorityQueue #优先队列 priorityQueue = PriorityQueue() #创建优先队列对象 priorityQueue.put(3) #插入元素 priorityQueue.put(78) #插入元素 priorityQueue.put(100) #插入元素 print(priorityQueue.queue) #查看优先级队列中的所有元素 priorityQueue.put(1) #插入元素
def __init__(self): """ Initialize your data structure here. """ self.que = LifoQueue()
def __init__(self): #a queue object consists of a stack and a set from queue import LifoQueue self.stack = LifoQueue() self.set = set()