All pastes #1608567 Raw Edit

Someone

public python v1 · immutable
#1608567 ·published 2009-10-10 00:33 UTC
rendered paste body
def two_queues_one_stack(queue_a_goal, queue_b_contents):    """Given the order in which items were enqueued into queue B, and the    desired order to have them enqueued into queue A, return a sequence of    operations to accomplish this according to the following constraints:        1) You cannot enqueue to queue B        2) You cannot dequeue from queue A         3) You are only allowed to to use a single stack for temporary storage    If this is possible, return the shortest list of instructions that will    accomplish this; otherwise, return None."""        # The three operations which can be performed.    op = ['STACK => QUEUE_A', 'QUEUE_B => QUEUE_A', 'QUEUE_B => STACK']    #Variables temp_stack, result & queue_a are assigned empty lists. Count is    #assigned 0.    temp_stack = []    result = []    queue_a = []    count = 0        """This algorithm attempts to find the sequence of operations(of the     allowed operations that would get queue_b_contents into queue_a in the     form of queue_a_goal."""        #While queue_a is not filled    while len(queue_a) != len(queue_a_goal):        #if the stack is not empty and the topmost object is the object needed:        if temp_stack != [] and temp_stack[-1] == queue_a_goal[count]:            #Pop and add the topmost object in the stack to queue_a and add            #the first allowed operation to result. Count is increased by 1.            queue_a.append(temp_stack.pop())            result.append(op[0])            count += 1        #Otherwise if queue_b_contents is not empty:        elif queue_b_contents != []:            #If the first element in queue_b_contents is not the object needed:            if queue_b_contents[0] != queue_a_goal[count]:                #The element is popped & added to the stack. The third allowed                #option is added to result.                temp_stack.append(queue_b_contents.pop(0))                result.append(op[2])            #Otherwise if the first element of queue_b_contents is needed:            elif queue_b_contents[0] == queue_a_goal[count]:                #The element is popped & added to queue_a. The second allowed                #operation is added to result. Count is increased by 1.                queue_a.append(queue_b_contents.pop(0))                result.append(op[1])                count += 1        #Otherwise if the topmost stack element is not needed and there are no        #more objects in queue_b_contents:        elif queue_b_contents == []:            #Solution is not possible so None is returned.            return None            #Result is returned when there is a solution.                 return result