1

I want to shuffle elements in an arbitrary number of stacks. For example if I have 3 stacks and the elements of the stack are as follows [ ["A", "C"] , ["B" , "D" ] ["E"] ].

After shuffling (removing from top of one stack and inserting on top of another stack) I get 6 possible states:

[[['A'], ['B', 'D', 'C'], ['E']], 
 [['A'], ['B', 'D'], ['E', 'C']],
 [['A', 'C', 'D'], ['B'], ['E']],
 [['A', 'C'], ['B'], ['E', 'D']], 
 [['A', 'C', 'E'], ['B', 'D'], []],
 [['A', 'C'], ['B', 'D', 'E'], []]]

I have written a method which does this but I dont think it is the pythonic way of doing it. What is the pythonic way of doing this?

You can find my code below.

def childstates( self ):
    children = []
    # iterate over self state one stack at a time
    for x in self.state:
        #if stack is not empty store the top element
        if len(x) > 0:
            ele = x[-1]
            visited = set([]) 
        # if stack is empty move to the next stack
        else:
            continue
        # each stack will produce n-1 combinations
        for i in range( len( self.state ) - 1 ):
            added = False
            index = 0
            # l2 => new list for each combination
            l2 = copy.deepcopy( self.state)
            for y in l2:
                if x == y:
                    y.pop()
                    index += 1
                    continue

                elif index in visited or added == True:
                    index += 1
                    continue
                else:
                    visited.add( index )
                    y.append( ele )
                    added = True
                    index += 1

            children.append( l2 )
    return children
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
huskywolf
  • 505
  • 1
  • 4
  • 12
  • Have you read [this](http://stackoverflow.com/questions/2853212/all-possible-permutations-of-a-set-of-lists-in-python)? – Shawn Mehan Oct 05 '15 at 18:17

1 Answers1

3

Seems like you could do this more easily with two for loops iterating over which stack to pop from, and which stack to push onto, respectively:

import itertools
import copy
stacks = [["A", "C"], ["B" , "D" ], ["E"]]
children = []
for i in range(len(stacks)):
    for j in range(len(stacks)):
        if i == j:
            continue
        cur_stack = copy.deepcopy(stacks)
        cur_stack[j].append(cur_stack[i].pop())
        print cur_stack
        children.append(cur_stack)

Result:

[['A'], ['B', 'D', 'C'], ['E']]
[['A'], ['B', 'D'], ['E', 'C']]
[['A', 'C', 'D'], ['B'], ['E']]
[['A', 'C'], ['B'], ['E', 'D']]
[['A', 'C', 'E'], ['B', 'D'], []]
[['A', 'C'], ['B', 'D', 'E'], []]
Kevin
  • 74,910
  • 12
  • 133
  • 166