Example #1
0
class AnimalQueue(object):
		
	def __init__(self):
		self.dogs = Queue()
		self.cats = Queue()


	def adoptDog(self):
		return self.dogs.pop()

	def adoptCat(self):
		return self.cats.pop()

	def adoptAny(self):

		if self.dogs.peek().order < self.cats.peek().order:
			return self.dogs.pop()
		else:
			return self.cats.pop()

	def enQueAnimals(self, a):
		if (type(a) == Dog):
			self.dogs.push(a)
		if (type(a) == Cat):
			self.cats.push(a)
Example #2
0
 def show(self):
     current = Queue()
     current.push(self)
     num = 1
     while not current.empty():
         line = []
         next_num = 0
         for i in range(num):
             node = current.front()
             current.pop()
             if node is None:
                 line.append('#')
                 continue
             else:
                 line.append(node.val)
             if node.left is not None:
                 current.push(node.left)
             else:
                 current.push(None)
             next_num += 1
             if node.right is not None:
                 current.push(node.right)
             else:
                 current.push(None)
             next_num += 1
         num = next_num
         print line
Example #3
0
def main():
    q = Queue()
    print('''
    0 - Exit
    1 - Print
    2 - Push
    3 - Head
    4 - Tail
    5 - Pop
    6 - Copy''')
    while True:
        try:
            k = int(input("-> "))
        except ValueError:
            k = "error"
        if k == 0:
            break
        elif k == 1:
            print(str(q))
        elif k == 2:
            elem = input("New element: ")
            q.push(elem)
        elif k == 3:
            print("Head: " + str(q.head()))
        elif k == 4:
            print("Tail: " + str(q.tail()))
        elif k == 5:
            q.pop()
            print("Popped")
        elif k == 6:
            cpy = Queue(original=q)
            print("Copy: " + str(cpy))
        else:
            print("Incorrect input")
Example #4
0
def general_collatz_tree(M, k=3, root=1):
    '''I am SO truly sorry for the running time
    of this algorithm. It has no choice but to be 
    exponential due to tree growth
    Generalization for all Collatz Trees'''
    tree = Graph()
    tree.add_vertex(root)
    frontier = Queue()
    frontier.push(root)
    primes = []
    p = k
    while True:
        try:
            p = prevprime(p)
        except:
            break
        primes.append(p)
    while len(tree) < M:
        x = frontier.pop()
        for i in range(len(primes) + 1):
            for tup in combinations(primes, i):
                y = x
                for prime in tup:
                    y = y * prime
                if y not in tree:
                    tree.add_vertex(y)
                    tree.add_edge(x, y)
                    frontier.push(y)
        if (x - 1) % k == 0:
            y = (x - 1) // k
            if y not in tree:
                tree.add_vertex(y)
                tree.add_edge(x, y)
                frontier.push(y)
    return tree
Example #5
0
def enCoder(text, series):
    q = Queue()
    for i in series:
        q.push(i)
    returnString = ""
    for i in text:
        if 'a' <= i <= 'z':
            returnString += chr((ord(i) - ord('a') + q.front()) % 26 +
                                ord('a'))
            q.push(q.pop())
        elif 'A' <= i <= 'Z':
            returnString += chr((ord(i) - ord('A') + q.front()) % 26 +
                                ord('A'))
            q.push(q.pop())
        else:
            returnString += i
    return returnString
    def _test_queue(self):
        queue = Queue()
        assert queue.is_empty()
        for item in self._test_items:
            queue.push(item)
        assert queue.size() == 4, "expected queue to be of size 4"
        assert (
            queue.peek() == "firstItem"
        ), "expected first item in queue to be firstItem"
        popped = queue.pop()
        assert queue.size() == 3
        assert queue.peek() == "secondItem"
        assert popped == "firstItem"

        while not queue.is_empty():
            queue.pop()
        assert queue.is_empty()
Example #7
0
 def test_pop(self):
     temp = Queue()
     for i in range(100):
         temp.push(i)
     PopOutput = []
     for i in range(100):
         PopOutput.append(temp.pop())
     self.assertEqual(temp.outputQueue(), [])
     self.assertEqual(PopOutput, list(range(100)))
Example #8
0
    def levelorder_traversal(self, node=ROOT):
        if node == ROOT:
            node = self.root

        queue = Queue()
        queue.push(node)
        while len(queue):
            node = queue.pop()
            if node.left:
                queue.push(node.left)
            if node.right:
                queue.push(node.right)
            print(node, end=" ")
Example #9
0
def display_bfs(vertex):
    visited = set()
    q = Queue()
    q.push(vertex)
    while not q.is_empty():
        current = q.pop()
        if current in visited:
            continue
        visited.add(current)
        print(current.get_key())
        for dest in current.get_neighbours():
            if dest not in visited:
                q.push(dest)
Example #10
0
    def LevelOrder(self, a_tree, a_visit):
        #search the tree in level-order
        temp = a_tree
        a_queue = Queue()

        a_queue.push(temp)
        while not a_queue.isEmpty():
            temp = a_queue.pop()
            a_visit(temp.val)
            if temp.left != None:
                a_queue.push(temp.left)
            if temp.right != None:
                a_queue.push(temp.right)
        print
Example #11
0
    def hasPathQueue(self, nodeA, nodeB):
        assert nodeA in self.graph, "nodeA is not in the graph "
        assert nodeB in self.graph, "nodeB is not in the graph "  

        queue = Queue()
        queue.push(nodeA)

        while not queue.is_empty():
            elem = queue.pop()
            neighbors = self.graph[elem]

            if elem == nodeB:
                return True
            queue.queue += neighbors.keys()
        return False
Example #12
0
    def bfs(self):
        queue = Queue()

        queue.add(self.root)

        while(queue.length() > 0):
            p = queue.pop()

            print(p.val),

            if p.left != None:
                queue.add(p.left)

            if p.right != None:
                queue.add(p.right)
Example #13
0
def colorirBFS(image, label, color, x, y, paint):
	fila = Queue()
	fila.put([x, y])

	while ( not fila.isEmpty() ):
		item = fila.pop()
		x = item[0]
		y = item[1]

		for k in range(0, 8):
			i, j = positions[k]
			if (image[y + j][x + i] == color and label[y + j][x + i] == 0):
				fila.put([x + i, y + j])
				label[y+j][x+i] = paint

	return label
        def _breadth_first(root):
            from Queue import Queue
            queue = Queue()

            bfs_order = []
            queue.push(root)
            while queue:
                node = queue.pop()
                bfs_order.append(node.val)

                if node.left:
                    queue.push(node.left)
                if node.right:
                    queue.push(node.right)

            return bfs_order
class TestGraph(unittest.TestCase):
    def setUp(self):
        self.queue = Queue()

    def test_is_empty_true(self):
        self.assertTrue(self.queue.is_empty())

    def test_is_empty_false(self):
        self.queue.push('a')
        self.assertFalse(self.queue.is_empty())

    def test_pop(self):
        self.queue.push('a')
        self.queue.push('b')
        self.assertEqual(self.queue.pop(), 'a')
        self.assertEqual(self.queue.pop(), 'b')
Example #16
0
def bfs(graph, start_node):
    queue = Queue()
    dist = {}
    parent = {}
    for node in graph.nodes():
        dist[node] = float("inf")
        parent[node] = None
    dist[start_node] = 0
    queue.push(start_node)
    while queue.items:
        node = queue.pop()
        for nbr in graph.get_neighbors(node):
            if dist[nbr] == float("inf"):
                dist[nbr] = dist[node] + 1
                parent[nbr] = node
                queue.push(nbr)
    return dist, parent
Example #17
0
    def doAStar(self, gridMap, start, goal):
            print "AStar"

	    #Create queue with only root node
	    q = Queue()
            begin = finish = None
            closest_start = closest_end = float("inf")
            for point in gridMap:
                dist_start = start.distanceTo(point)
                dist_end = goal.distanceTo(point)
                if dist_start < closest_start:
                    closest_start = dist_start
                    begin = point
                if dist_end < closest_end:
                    closest_end = dist_end
                    finish = point
	    q.add(Node(begin, Cost(point.distanceTo(finish), 0), []))

	    bestSoFar = float("inf")
	    bestNode = None
	    while(True):
	        parent = q.pop()
	        if (parent == None or parent.cost.f > bestSoFar):
		    break

	        for child in parent.point.accessiblePoints:
		    if parent.hasPointInPath(child):
		        continue

		    g = parent.cost.g + parent.point.distanceTo(child)
		    h = child.distanceTo(finish)

		    cost = Cost(g + h, g)
		    node = Node(child, cost, parent.path + [parent.point])
		    q.add(node)

		    if (h == 0 and bestSoFar > g):
		        bestSoFar = g
		        bestNode = node


	    if bestNode == None:
	        return None
	    return bestNode.path + [goal]
Example #18
0
    def doAStar(self, gridMap, start, goal):
        print "AStar"

        #Create queue with only root node
        q = Queue()
        begin = finish = None
        closest_start = closest_end = float("inf")
        for point in gridMap:
            dist_start = start.distanceTo(point)
            dist_end = goal.distanceTo(point)
            if dist_start < closest_start:
                closest_start = dist_start
                begin = point
            if dist_end < closest_end:
                closest_end = dist_end
                finish = point
        q.add(Node(begin, Cost(point.distanceTo(finish), 0), []))

        bestSoFar = float("inf")
        bestNode = None
        while (True):
            parent = q.pop()
            if (parent == None or parent.cost.f > bestSoFar):
                break

            for child in parent.point.accessiblePoints:
                if parent.hasPointInPath(child):
                    continue

                g = parent.cost.g + parent.point.distanceTo(child)
                h = child.distanceTo(finish)

                cost = Cost(g + h, g)
                node = Node(child, cost, parent.path + [parent.point])
                q.add(node)

                if (h == 0 and bestSoFar > g):
                    bestSoFar = g
                    bestNode = node

        if bestNode == None:
            return None
        return bestNode.path + [goal]
Example #19
0
class ThreadPool(object):

    def __init__(self, workers=5):
        self._queue = Queue()
        assert size > 0
        threads = []
        for i in xrange(workers):
            t = Thread(target=self._worker)
            t.setDaemon(True)
            t.start()
            threads.append(t)

    def _worker(self):
        while True:
            try:
                func, args = self._queue.pop()
                func(*args)
            except Exception as e:
                _log.error("Error occured in worker: %r", e)

    def execute(self, func, args=()):
        self._queue.push((func, args))
Example #20
0
class Broker(object):
    def __init__(self, send_ws_message):
        self.message_queue = Queue()
        self.connections = ConnectionMap()
        self.send = send_ws_message

    def listen_on_queue(self):
        while True:
            try:
                message = self.message_queue.pop()
                if message is not None:
                    self._broadcast_message(message)
                    print 'message broker got:', message.value
                time.sleep(0.1)
            except Exception as e:
                print "Something went wrong ", e

    def _broadcast_message(self, message):
        for connection in self.connections.get_hash_list():
            while connection is not None:
                try:
                    self.send(connection.connection, message.value)
                except Exception as e:
                    print "exception in broadcasting to this connection, closing it ", e
                    connection.connection.close()
                    self.connections.remove(connection.key)
                connection = connection.next_node

    def add_connection(self, address, connection):
        self.connections.put(address, connection)

    def remove_connection(self, address):
        self.connections.remove(address)

    def add_message_to_queue(self, message):
        self.message_queue.add(message)
Example #21
0
def main():
	resp = Queue()

	img  = cv2.imread('componentes.png', 0)
	img = cv2.copyMakeBorder(img, 1,1,1,1, cv2.BORDER_CONSTANT, -1)
	label= np.zeros(img.shape, np.uint8)

	x, y = findNext(label)
	paint = 0

	while(x != -1):
		paint += 1
		color = img[y][x]
		label = colorirBFS(img, label, color, x, y, paint)
		resp.put(label)

		x, y = findNext(label)

	print( str(paint) + ' componentes!' )

	position = 1
	while( not resp.isEmpty() ):
		showImage(resp.pop(), position)
		position += 1
Example #22
0
def find_shortest_paths(src):
    parent = {src: None}
    distance = 0
    path = []
    visited = set()
    q = Queue()
    q.push(src)
    visited.add(src)
    while not q.is_empty():
        current = q.pop()
        if current.get_key() == "kevin bacon":
            tmp = current
            while tmp is not None:
                path.append(tmp)
                distance += 1
                tmp = parent[tmp]
            break
        for dest in current.get_neighbours():
            if dest not in visited:
                visited.add(dest)
                parent[dest] = current
                q.push(dest)

    return (path, distance)
Example #23
0
        # Keep the running total
        total_inventory_qty += qty

    elif choice == 2:
        qty_needed = int(input("How many are you looking to sell?"))
        if qty_needed > total_inventory_qty:
            print("You do not have that many available for sale.\n\n")
            # This statement makes the loop start back at the menu
            continue
        else:
            total_popped = 0
            total_sale = 0.0

            # These next 5 lines are the key to keeping track of where you are
            qty_popped = inventory_system_qty.pop()
            total_inventory_qty -= qty_popped
            price = inventory_system_price.pop()
            total_sale += (qty_popped * price)
            total_popped += qty_popped
            # Keep popping until we have enough
            while total_popped < qty_needed:
                qty_popped = inventory_system_qty.pop()
                total_inventory_qty -= qty_popped
                price = inventory_system_price.pop()
                total_sale += (qty_popped * price)
                total_popped += qty_popped

            # We should have popped enough, but did we pop too many?  Push the extra back on.
            if total_popped > qty_needed:
                overage = total_popped - qty_needed
Example #24
0
from Stack import Stack
from Queue import Queue

myStack = Stack()
myStack.push(12)
myStack.push(34)
myStack.push(78)
myStack.show()
myStack.pop()
myStack.show()

myQueue = Queue()
myQueue.push(54)
myQueue.push(67)
myQueue.push(13)
myQueue.show()
myQueue.pop()
myQueue.show()
                    elif profit < 0:
                        print(
                            f"Those shares put you at a loss of ${abs(profit)}"
                        )
                    else:
                        print("You have made no profit for these shares")

            elif choice == "F":
                # If the user chose FIFO at the beginning this will sell the shares using the Queue
                current = MyQueueShare.head()
                if current == sell:
                    selling = sold * current
                    bought = MyQost.head() * sell
                    profit = selling - bought
                    Profit += profit
                    MyQueueShare.pop()
                    MyQost.pop()
                    if profit > 0:
                        print(f"Your profit is ${profit}")
                    elif profit < 0:
                        print(f"You are at a loss of ${abs(profit)}")
                    else:
                        print("You have made no profit for these shares")

                elif current > sell:
                    current -= sell
                    selling = sold * sell
                    bought = MyQost.head() * sell
                    profit = selling - bought
                    Profit += profit
                    MyQueueShare.pop()
Example #26
0
from Queue import Queue

queue = Queue()
queue.put('a')
queue.put('b')
queue.put('c')
queue.put('d')  # size 4 list - 'a' 'b' 'c' 'd'
print(queue)
queue.pop()
print(queue)
queue.pop()
queue.pop()
queue.pop()
print(queue)
print(queue.size())
Example #27
0
def RR(processes, tcs, simout,tslice,rradd):
    """
    The RR algorithm
    @param processes: list of processes to be scheduled
    @param tcs: time required to perform **HALF** context switches, i.e. time
    needed to for either switching in or switching out
    @param simout: the out file object
    """

    # print all processes
    for p in processes:
        s = 's'
        if p.num_bursts == 1:
            s = ''
        print('Process', p.name, '[NEW] (arrival time', p.arrival, 'ms)', p.num_bursts, 'CPU burst{}'.format(s))

########################## Variable Initialization #############################

    # clock for counting time
    clock = 0 

    # queue of RR, could be changed to accommodate priority queue
    if (rradd==Precedence.END): queue = Queue()
    else: queue=Queue('stack')

    # List of processes before arrival
    pre_arrival = [] 

    # List of processes currently doing IO. Note that this list must be sorted
    # at all times
    ios = []

    # Current bursting process. If the CPU is idle, this variable is set to None
    bursting = None

    # Indicates whether the CPU is doing the first half of the context switch
    switch_in = False

    # Indicates whether the CPU is doing the second half of the context switch
    switch_out = False

    # Preparation counter for context switch. If preparation == 0, context
    # switch is done
    preparation = tcs

    # The process that's going to IO. After a process ends its CPU burst, it's
    # "going" to IO, but it only actually goes to IO after the context switch
    # is done
    to_io = None

    # List of burst times to calculate the metrics
    burst_time = []

    #number of preemption
    preemption=0

    #flag to determine whether exit normally or preempted

    preempt_flag=False


    burst_number=0

    preced='END' if rradd==Precedence.END else 'BEGINNING'

################################## Overhead ####################################

    print('time 0ms: Simulator started for RR with time slice {}ms and rr_add to {}'.format(int(tslice),preced),queue)

    # Put all processes to either the queue (if arrival time is 0) or the
    # pre_arrival list
    for p in processes:
        if p.arrival == 0:
            queue.push(p)
            print('time {}ms: Process {} arrived; placed on ready queue'.format(clock, p.name), queue)
        else:
            pre_arrival.append(p)
    # Find the burst number in total
    for p in processes:
        burst_number += p.num_bursts
    # Select a process to burst if the queue is not empty
    if len(queue) != 0:
        bursting = queue.pop()
        bursting.wait.append(0)
        switch_in = True
        preparation = tcs - 1

################################# Simulation ###################################
    #ts is use to keep track of tslice
    ts=tslice

    while (True):
        """
        The workflow:
        1. taking out a process from bursting
        2. add a new process to burst
        3. check for any completed IO
        4. check for any process arrival
        For ties in any of the above events, break with names in alphabetical
        order, i.e. Process A is should finish IO ahead of Process B
        """
        
        # Increment time first
        clock += 1
        # Do a CPU burst
        if bursting != None and (not switch_in):
            bursting.timelist[0] -= 1
            bursting.cpu_time += 1
            burst_time[-1] += 1
            ts-=1
            # If a process finished bursting, check if the process is
            # terminating. If not, put it to IO. Also turns on context switches.
            if bursting.timelist[0] == 0:
                bursting.timelist.pop(0)
                bursting.num_bursts -= 1
                if bursting.num_bursts == 0:
                    print('time {}ms: Process {} terminated'.format(clock, bursting.name), queue)
                else:
                    s = 's'
                    if bursting.num_bursts == 1:
                        s = ''
                    if clock < 1000 or not __debug__:
                        print('time {}ms: Process {} completed a CPU burst; {} burst{} to go'.format(clock, bursting.name, bursting.num_bursts, s), queue)
                        print('time {}ms: Process {} switching out of CPU; will block on I/O until time {}ms'.format(clock, bursting.name, clock + bursting.timelist[0] + tcs), queue)
                    to_io = bursting
                switch_out = True
                bursting.cpu_time = 0
                preparation = tcs + 1
                bursting = None
            elif ts==0 and len(queue):
                if clock < 1000 or not __debug__:
                    print('time {}ms: Time slice expired; process {} preempted with {}ms to go'.format(clock,bursting.name,bursting.timelist[0]),queue)
                switch_out=True
                preparation = tcs + 1
                to_io=bursting
                bursting=None
                preemption += 1
                preempt_flag=True
            elif ts==0 and len(queue)==0:
                ts=tslice

        # Doing context switch and if context switch done, put a process into
        # bursting
        if switch_in:
            if preparation != 0:
                preparation -= 1
            else:
                switch_in = False
                burst_time.append(0)
                if clock < 1000 or not __debug__:
                    if (bursting.cpu_time == 0):
                        print('time {}ms: Process {} started using the CPU for {}ms burst'.format(clock, bursting.name, bursting.timelist[0]), queue)
                    else:
                        print('time {}ms: Process {} started using the CPU with {}ms burst remaining'.format(clock,bursting.name,bursting.timelist[0]),queue)
        
        #push the preempt process in
        if switch_out:
            if ((preparation-1)==0 and (preempt_flag)):
                switch_out=False
                preempt_flag=False
                queue.push(to_io)
                to_io=None
                ts=tslice

        # Do IO for each process and check if any process completed IO. Note
        # that the IO list must always be in alphabetical order
        remove = []
        for p in ios:
            p.timelist[0] -= 1
            if p.timelist[0] == 0:
                p.timelist.pop(0)
                queue.push(p)
                p.wait.append(0)
                remove.append(p)
                if clock < 1000 or not __debug__:
                    print('time {}ms: Process {} completed I/O; placed on ready queue'.format(clock, p.name), queue)
        for p in remove:
            ios.remove(p)
        ios.sort()

        # Decrement arrival time and check if any process arrives
        remove.clear()
        for p in pre_arrival:
            p.arrival -= 1
            if p.arrival == 0:
                queue.push(p)
                p.wait.append(0)
                remove.append(p)
                if clock < 1000 or not __debug__:
                    print('time {}ms: Process {} arrived; placed on ready queue'.format(clock, p.name), queue)
        for p in remove:
            pre_arrival.remove(p)

        # Doing switch out. If done, put a process into IO.
        if switch_out:
            preparation -= 1
            if preparation == 0:
                switch_out = False
                if to_io != None:
                    ios.append(to_io)
                    ios.sort()
                to_io = None
                ts=tslice

        # If the CPU is idle and the queue is not empty, pop the queue and start
        # switching in
        if bursting == None and len(queue) != 0 and (not switch_out) and (not switch_in):
            bursting = queue.pop()
            switch_in = True
            preparation = tcs - 1

        # For each process that's still in the queue, increment its wait time
        # for metrics calculation
        for p in queue:
            p.wait[-1] += 1

        # If there isn't a process anywhere, break the simulation, and directly
        # add tcs to the clock to account for the final context switch
        if len(pre_arrival) == 0 and len(ios) == 0 and bursting == None and len(queue) == 0 and to_io == None:
            print('time {}ms: Simulator ended for RR'.format(clock + tcs), queue)
            break

############################# metrics calculation ##############################

    # Calculate average burst time

    avg_burst = sum(burst_time) / burst_number

    # Calculate average wait time by appending all wait times from all processes
    # together, then get the average
    avg_wait = []
    for p in processes:
        avg_wait += p.wait
    avg_wait = sum(avg_wait) / len(avg_wait)

    # Create the metrics data. 
    # Note that avg_turnaround = avg_burst + avg_wait + tcs * 2
    # Here FCFS doesn't have preemptions.
    data = 'Algorithm RR\n' + \
           '-- average CPU burst time: {:.3f} ms\n'.format(avg_burst) + \
           '-- average wait time: {:.3f} ms\n'.format(avg_wait) + \
           '-- average turnaround time: {:.3f} ms\n'.format(avg_burst + avg_wait + (len(burst_time))*tcs * 2/(burst_number)) + \
           '-- total number of context switches: {}\n'.format(len(burst_time)) + \
           '-- total number of preemptions: {}\n'.format(preemption) + \
           '-- CPU utilization: {:.3f}%\n'.format(sum(burst_time) / (clock + tcs) * 100)
    simout.write(data)
Example #28
0
                    toCrawl.append(next_link)
                lock_all_queues.release()
        # print " Thread #" + str(thread_number) + " : Finished"
        semaphore.release()

# Procedure Init
if __name__ == "__main__":
    toCrawl.append(homeurl)
    i = 0
    while 1:
        semaphore.acquire()

        # Check for Number of Docs created
        lock_doc_id.acquire()
        if doc_id > DOCS_TO_SAVE:
            print("%d Documents created and exiting.", DOCS_TO_SAVE)
            break
        lock_doc_id.release()

        lock_all_queues.acquire()
        if toCrawl:
            link  = toCrawl.pop()
            crawled.append(link)
            lock_all_queues.release()
            i = i + 1
            t = threading.Thread(target=threads_work, args=(link,i))
            t.start()
            # print "Started Thread #" + str(i) + "\n"
        else:
            semaphore.release()
            lock_all_queues.release()
Example #29
0
	print("Queue Test Completed.")
	print("-------------------------------------------------------")
	print("This is the Stack Test. Added 10 elements to the stack:")
	c = Stack()
	c.push(1)
	c.push(2)
	c.push(3)
	c.push(4)
	c.push(5)
	c.push(6)
	c.push(7)
	c.push(8)
	c.push(9)
	c.push(10)
	c.checkSize()
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	print("Popped off: %s" % c.pop())
	c.checkSize()
	print("Stack Test completed.")
	print("-------------------------------------------------------")
	print("This is the Graph Test: ")
	graph = Graph()
	graph.addVertex(1)
Example #30
0
            print("Invalid value!")

    q = Queue(capacity)
    while True:
        cls()
        print_status(q)
        choice = dictionary.get(input("> ").lower(), -1)
        if choice == 1:
            value = input("value> ")
            while not len(value) > 0:
                print("Value cannot be empty.")
                value = input("value> ")
            if not q.append(value):
                print("Queue is full")
        elif choice == 2:
            value = q.pop()
            if not value:
                print("Queue is empty")
        elif choice == 3:
            q.sort()
        elif choice == 0:
            break
        else:
            print("Invalid command")
            print_help()
        q.print()
        if q.is_empty():
            print("The queue is empty")
        else:
            print("The queue is not empty")
if a.lower() == 'stack':
Example #31
0
    return returnString


out = enCoder(text, series)
print(out)
print(deCoder(out, series))

q = Queue()

for i in series:
    q.push(i)

output = ""
for i in text:
    if 'a' <= i <= 'z':
        number = q.pop()
        output += str(chr(((ord(i) - ord('a') + number) % 26) + ord('a')))
        q.push(number)
    elif 'A' <= i <= 'Z':
        number = q.pop()
        output += str(chr(((ord(i) - ord('A') + number) % 26) + ord('A')))
        q.push(number)
    else:
        output += i

print(output)

q = Queue()

for i in series:
    q.push(i)
Example #32
0
class Search:
	def __init__ (self, init_str, arg, cost_flag):
		self.cost_flag = cost_flag
		self.tree = Tree()
		self.arg = arg
		init_state = State(0,0,init_str) 

		self.length = len(init_str) #length of puzzle used for making moves
		
		#data structure for BFS is a Queue import Queue class for L
		if arg == "BFS":
			self.L = Queue()
			self.L.put(init_state)
		
		else:
			if arg not in ["DFS","UCS","A-STAR","GS"]:
				arg = "DFS" #if not a valid search default to DFS
				
			self.L = [init_state] #only BFS uses Queue every other search will use a list
		

		self.expanded = [] #list of expanded states
		self.cur_tree_id = 1 #unique tree id per state added to the tree
		self.tree.create_node(init_state.string,init_state.tid) #creates the root node of the search tree

	# returns the needed node from structure L
	# in GS,UCS,A-STAR it requires a min heap.
	# use a list but sort the list by the given f-costs
	# UCS : "cost to of a path(number of moves)"
	# A-STAR : "path cost + number of tiles misplaced"
	# GS : "number of tiles misplaced"
	# since list does not have a remove from front
	# reverse the sorted list and pop.
	def get(self):
		if isinstance(self.L, Queue):
			state = self.L.get()
		
		elif isinstance(self.L, list):
			if self.arg == "UCS":
				self.L.sort(key = lambda n: (n.cost, n.tid), reverse=True) 

			elif self.arg == "A-STAR":
				self.L.sort(key = lambda n: ((n.cost + n.num_misplaced),n.tid), reverse=True)

			#returns lowest f cost where f(n)=h(n)
			elif self.arg == "GS":
				self.L.sort(key = lambda n: (n.num_misplaced,n.tid), reverse=True)

			state = self.L.pop()
			return state

	def put(self,state):
		if isinstance(self.L, Queue):
			self.L.put(state)
		
		elif isinstance(self.L, list):
			self.L.append(state)
	
	def is_empty(self):
		if isinstance(self.L, Queue):
			return self.L.empty()
		
		elif isinstance(self.L, list):
			return not bool(self.L) #bool ([]) returns false 
	
	# generic search will handle all searches
	# the node to chosen for the search will depend on the get method 
	def search(self):
		while not self.is_empty():
			node = self.get()			
			if self.is_goal(node):
				break
			else:
				self.expand(node)

		self.path_to_goal(node)
	
	def expand(self,state):
		if not self.is_in_expanded(state):
			self.expanded.append(state) #
			for i in range(self.length):
				
				if self.cost_flag: #cost will be the steps for x 

					cost = abs(state.string.index("x") - i)  
					
				else:
					cost = state.cost + 1 #total path cost
				
				successor = State(self.cur_tree_id,cost, state.string) #create a copy of node to apply move then add to L and tree
				self.cur_tree_id += 1
				if i != state.string.index('x'): #don't move x into itself
					successor.move(i)
					self.put(successor) #put state into data structure L 
					self.add_to_tree(successor,state)
				


	def is_in_expanded (self, state):
		# checks expanded if a state as already been exanded
		return state in self.expanded

	def is_goal (self, state):
		# returns true if state as no misplaced tiles
		return not bool(state.num_misplaced) 

	def add_to_tree (self, state, parent):
		self.tree.create_node(state.string, state.tid, parent=parent.tid)

	def path_to_goal (self, goal):
		node = self.tree[goal.tid] 
		move_list  = [node]
		
		while not node.is_root():
			node = self.tree[node.bpointer]
			move_list.append(node)
		
		#reverse move_list because first node is the goal and you want first node to be root Path(root->goal)
		move_list = list(reversed(move_list))
		print "board movements start at the left index 0 "
		print "example initial wxb step 1: move 0 xwb"  
		print "step 0: ", move_list[0].tag
		for i in range(1, len(move_list)):
			print "step %i: " % i, "move %i"% move_list[i].tag.index("x"), move_list[i].tag
    nxt = []
    if cur in gra:
        nxt = gra[cur]
    for node in nxt:
        if node not in covered:
            covered.add(node)
            q.put(node)

#DFS
q = []
covered = set([s])
q.append(s)
connected = False

while q:
    cur = q.pop()
    if cur == t:
        connected = True
        break
    nxt = []
    if cur in gra:
        nxt = gra[cur]
    for node in nxt:
        if node not in covered:
            covered.add(node)
            q.append(node)

#cc BFS
cc = {}
countc = 1
covered = set([])
Example #34
0
            2.sell stock
            3.see your profit
            4.close program""")
    answer = int(input())
    if answer == 1:
        print("How much did paper did you buy?")
        stock = input()
        print("How much was it per unit? please only the number")
        money = input()
        totalstock.push(stock)
        totalmoney.push(money)

    elif answer == 2:
        print("How much are you selling?")
        reqstock = int(input())
        print("For how much per unit? please only the number")
        money = int(input())
        oldstock = int(totalstock.pop())
        oldmoney = int(totalmoney.pop())
        profit = (money - oldmoney) * reqstock
        while reqstock > oldstock:
            reqstock = reqstock - oldstock
            oldstock = totalstock.pop()
        if reqstock < oldstock:
            oldstock = oldstock - reqstock
            totalstock.push(oldstock)
            totalmoney.push(oldmoney)

    elif answer == 3:
        print("$" + str(profit))