Question

I'm trying to define a function with two stacks (collection deque stacks) where items from the first stack is popped and appended to an empty stack and then both stacks are sent to an external function. I need to repeat this process twice as follows but do not want to repeat the code so I wonder if there is some efficient way to do this with a while loop - break statement or iterator?

import collections
from collections import deque

sentence = [0,1,2,3,4]

stack1 = deque(sentence)  # contains sentence
stack2 = deque([])          # empty, awaiting items from stack1

for i in range(0,len(sentence)): 
    stack1.popleft(i)     # pop first item to the left from stack1;0 ([**0**,1,2,3,4])
    stack2.append(i)      # append it to stack 2; stack2 = ([0])

    function(stack1, stack2)   #run stack1 and stack2 in external functions
   # Repeating
    stack1.popleft(i) again    #pop (only) once more from stack1; 1 ([**1**,2,3,4])
    stack2.append(i) again     # append it to stack2; stack2 = ([0, 1])

   function (stack1, stack2)   # run the external function again

ENDFOR - end function, no more rounds

Was it helpful?

Solution

I would suggest using a simple function to handle this:

from collections import deque

sentence = [0, 1, 2, 3, 4]

stack1 = deque(sentence)
stack2 = deque([])


print(stack1, stack2)


def do_it(st1, st2):
    item = st1.popleft()
    st2.append(item)

while stack1:
    do_it(stack1, stack2)
    # Do some stuff here
    do_it(stack1, stack2)

print(stack1, stack2)

Output:

(deque([0, 1, 2, 3, 4]), deque([]))
(deque([]), deque([0, 1, 2, 3, 4]))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top