Ejemplo n.º 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)
Ejemplo n.º 2
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")
Ejemplo n.º 3
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
Ejemplo n.º 4
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)))
Ejemplo n.º 5
0
 def test_clear(self):
     temp = Queue()
     for i in range(100):
         temp.push(i)
     self.assertEqual(temp.outputQueue(), list(range(100))[::-1])
     temp.clear()
     self.assertEqual(temp.outputQueue(), [])
     for i in range(100):
         temp.push(i)
     self.assertEqual(temp.outputQueue(), list(range(100))[::-1])
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
class AtomQueue(UrlQueue):
    def __init__(self):
        self.queue = Queue()
        self.timeout = 10

    def pop(self):
        try:
            return self.queue.get(block=True, timeout=self.timeout)
        except Empty:
            return None

    def push(self, request):
        if not isinstance(request, Request):
            raise Exception('request must be urllib2.Request')
        self.queue.push(request)
Ejemplo n.º 8
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
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')
Ejemplo n.º 10
0
def merge(a, b):
    merge_queue = Queue()
    while not a.is_empty() or not b.is_empty():
        if a.is_empty():
            merge_queue.push(b.pop())
        elif b.is_empty():
            merge_queue.push(a.pop())
        elif a.peek() < b.peek():
            merge_queue.push(a.pop())
        elif a.peek() > b.peek():
            merge_queue.push(b.pop())
        else:
            merge_queue.push(a.pop())
            merge_queue.push(b.pop())

    return merge_queue
    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()
Ejemplo n.º 12
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
Ejemplo n.º 13
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
Ejemplo n.º 14
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))
Ejemplo n.º 15
0
 def __repr__(self):
     if not self.root:
         return None
     else:
         tempQ = Queue()
         toPrint = Queue()
         tempQ.push(self.root)
         while not tempQ.empty():
             currentNode = tempQ.get()
             toPrint.push(currentNode)
             if currentNode.left:
                 tempQ.push(currentNode.left)
             if currentNode.right:
                 tempQ.push(currentNode.right)
         return toPrint.__repr__()
Ejemplo n.º 16
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)
Ejemplo n.º 17
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=" ")
Ejemplo n.º 18
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
        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
Ejemplo n.º 20
0
class Stack:
    def __init__(self, size):
        self.csize = size
        self.stackQueue = Queue(size)
        self.helpQueue = Queue(size)

    def swap(self):
        tempQueue = self.stackQueue
        self.stackQueue = self.helpQueue
        self.helpQueue = tempQueue

    def push(self, value):
        if (self.stackQueue.realsize == self.csize):
            print "This Stack is full"
            return
        self.stackQueue.push(value)

    def poll(self):
        if self.stackQueue.isEmpty():
            print "This Stack is empty"
            return
        while self.stackQueue.realsize != 1:
            self.helpQueue.push(self.stackQueue.poll())
        res = self.stackQueue.poll()
        self.swap()
        return res

    def peek(self):
        if self.stackQueue.isEmpty():
            print "This Stack is empty"
            return
        while self.stackQueue.currentSize() != 1:
            self.helpQueue.push(self.stackQueue.poll())
        res = self.stackQueue.ppll()
        self.helpQueue.push(res)
        self.swap()
        return res
Ejemplo n.º 21
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
            except ValueError:
                try:
                    cost = float(cost)
                    break
                except ValueError:
                    print("Give me a number please")

        # Adds these values to the Stack if chosen
        Shares += buy
        if choice == "L":
            MyStackShare.push(buy)
            MyCoSt.push(cost)

        # Adds these values to the Queue if chosen
        elif choice == "F":
            MyQueueShare.push(buy)
            MyQost.push(cost)

# They can sell that stock and state the price
    elif action == 'SELL' or action == '2' or action == "S":
        sell = 0
        while sell != "Hello World":
            sell = input("\nHow many shares do you wish to SELL?" "\n>>>")
            try:
                sell = int(sell)
                break
            except ValueError:
                print("Type a whole number please")

        sold = 0
        while sold != 'Hello World':
Ejemplo n.º 23
0
choice = 0

while choice != 5:
    print("Please select an option from the menu below:")
    print("1. Add items to inventory")
    print("2. Sell items in inventory")
    print("3. See total quantity in inventory")
    print("4. See total profit")
    print("5. Exit Program")
    choice = int(input(">"))

    if choice == 1:
        # get the qty and price, push them onto the Stacks
        qty = int(input("How many are you adding?"))
        price = float(input("How much does each cost?"))
        inventory_system_qty.push(qty)
        inventory_system_price.push(price)
        print("Added to inventory. \n\n")

        # 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
Ejemplo n.º 24
0
from Stack import Stack
from Queue import Queue
import random

stack = Stack()
que = Queue()

for x in range(10):
    num = random.randint(-10, 10)
    stack.push(num)
    print num,
    print "Min element in stack = ", stack.getMin()
    que.push(num)

print "Push Order"

stack.printStack()
que.printQ()
Ejemplo n.º 25
0
totalmoney = Queue()
profit = 0
answer = 0
while answer != 4:
    print("""Please type the number to select what you would like to do
            1.buy stock
            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
Ejemplo n.º 26
0
def test_it():
    q = Queue()
    for i in range(100):
        q.push(i)
        assert q.size() == i + 1
Ejemplo n.º 27
0
from Queue import Queue

queue = Queue()

#Insert elements
queue.push(1)
queue.push(3)
queue.push("a")
queue.push(True)

#Get front data
print(queue.front())

#Get back data
print(queue.back())

#Check if is empty
print(queue.empty())

#Print queue
print(queue)

#Remove elements
print(queue.pop())
print(queue.pop())
print(queue.pop())
print(queue.pop())


#Check again if queue is empty
print(queue.empty())
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
def SJF(processes, tcs, simout,lamb,alpha):
    """
    The SJF 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{} (tau {}ms)'.format(s,int(1/lamb)))

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

    # clock for counting time
    clock = 0 

    # queue of FCFS, could be changed to accommodate priority queue
    queue = Queue('pq')

    # 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 = []

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

    print('time 0ms: Simulator started for SJF', 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:
            p.tau=int(1/lamb)
            queue.push((p.tau,p))
            print('time {}ms: Process {} (tau {}ms) arrived; placed on ready queue'.format(clock, p.name,p.tau), queue)
        else:
            pre_arrival.append(p)

    # Select a process to burst if the queue is not empty
    if len(queue) != 0:
        bursting = queue.pop()[1]
        bursting.wait.append(0)
        switch_in = True
        preparation = tcs - 1

################################# Simulation ###################################

    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
            
            # 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 = ''
                    new_tau = tau_function(bursting,alpha)
                    if clock < 1000 or not __debug__:
                        print('time {}ms: Process {} (tau {}ms) completed a CPU burst; {} burst{} to go'.format(clock, bursting.name, bursting.tau,bursting.num_bursts, s), queue)
                        print('time {}ms: Recalculated tau ({}ms) for process {}'.format(clock,new_tau,bursting.name),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)
                    bursting.tau=new_tau
                    to_io = bursting
                switch_out = True
                bursting.cpu_time = 0
                preparation = tcs + 1
                bursting = None

        # 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__:
                    print('time {}ms: Process {} (tau {}ms) started using the CPU for {}ms burst'.format(clock,bursting.name,bursting.tau, bursting.timelist[0]), queue)
        
        # 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.tau,p))
                p.wait.append(0)
                remove.append(p)
                if clock < 1000 or not __debug__:
                    print('time {}ms: Process {} (tau {}ms) completed I/O; placed on ready queue'.format(clock, p.name,p.tau), 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:
                p.tau=int(1/lamb)
                queue.push((p.tau,p))
                p.wait.append(0)
                remove.append(p)
                if clock < 1000 or not __debug__:
                    print('time {}ms: Process {} (tau {}ms) arrived; placed on ready queue'.format(clock, p.name,p.tau), 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

        # 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()[1]
            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[1].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 SJF'.format(clock + tcs), queue,'\n')
            break

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

    # Calculate average burst time
    avg_burst = sum(burst_time) / len(burst_time)

    # 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 SJF\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 + tcs * 2) + \
           '-- total number of context switches: {}\n'.format(len(burst_time)) + \
           '-- total number of preemptions: 0\n' + \
           '-- CPU utilization: {:.3f}%\n'.format(sum(burst_time) / (clock + tcs) * 100)
    simout.write(data)
Ejemplo n.º 30
0
def General_Search(graph, search_method, d):

    start = time.time()

    print("Running: " + search_method)
    if search_method == 'IDDFS':
        print("L = " + str(d) + "     Expanded     Queue")
    else:
        print("         Expanded     Queue")

    # root = g.get_vertex('S')
    # destination = g.get_vertex('G')

    root = g.get_vertex('S')
    destination = g.get_vertex('G')

    # queue for unweighted search
    queue = Queue()
    queue.push([root])

    #heap for weighted search
    path = Path()
    path.add_vertex(root)
    heap = Heap()
    heap.push(path)

    visited = []  # visited used by BMS

    while 1:

        if search_method == 'UCS' or search_method == 'GS' or search_method == 'AS'\
                or search_method == 'HC' or search_method == 'BMS':
            nodes = heap.get_left_peek().get_vertexes()
            nodes.reverse()
        else:
            nodes = queue.get_left_peek()  # get the left peek without popping

        print('         ' + nodes[0].id, end='              ')
        # use the given search method
        # DFS
        if search_method == 'DFS':
            print(queue)
            dfs_expand(queue)
        # BFS
        elif search_method == 'BFS':
            print(queue)
            bfs_expand(queue)

        elif search_method == "DLS":
            print(queue)
            dls_expand(queue, 2)

        elif search_method == 'IDDFS':
            print(queue)
            dls_expand(queue, d)

        elif search_method == 'UCS':
            print(heap)
            ucs_expand(heap)

        elif search_method == 'GS':
            print(heap.str_heuristic())
            gs_expand(heap)

        elif search_method == 'AS':
            print(heap.str_a_star())
            as_expand(heap)

        elif search_method == 'HC':
            # if len(nodes) > 1:
            #     unexplored_children = list(nodes[0].get_connection())
            #     unexplored_children.remove(nodes[1])
            #
            #     # print(unexplored_children)
            #
            #     if len(unexplored_children) != 0: # there is unvisited node(s) from this node
            #         print('         ' + nodes[0].id, end='              ')
            #         print(heap.str_heuristic())  # use the same on as the Greedy Search
            #
            #         hc_expand(heap)
            #
            # else:
            print(heap.str_heuristic())  # use the same on as the Greedy Search

            hc_expand(heap)

        elif search_method == 'BMS':
            visited.append(nodes[0])
            print(heap.str_heuristic())  # use the same on as the Greedy Search
            bms_expand(heap, 2, visited)

        # the if's must be in this order: check destination before searching
        # otherwise IDDFS won't work
        if nodes[0] == destination:
            end = time.time()
            print(
                "         goal reached! " + "Time taken by " + search_method +
                " is", end - start, "seconds")
            return nodes[0]

        if queue.isEmpty() or heap.isEmpty():
            if search_method == 'IDDFS':
                d = d + 1
                General_Search(g, 'IDDFS', d)  # use recursion for IDDFS

            # print("No solution, terminated")
            return
Ejemplo n.º 31
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)
Ejemplo n.º 32
0
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	print("Dequeued: %s" % c.Remove())
	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())
Ejemplo n.º 33
0
            returnString += chr((ord(i) - ord('A') - q.front()) % 26 +
                                ord('A'))
            q.push(q.pop())
        else:
            returnString += i
    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)