2015-10-05 62 views
1

我想洗牌任意堆棧中的元素。例如,如果我有3個堆棧,堆棧的元素如下: [ ["A", "C"] , ["B" , "D" ] ["E"] ]Pythonic方式洗牌堆棧

洗牌(從一個堆棧的頂部取出並插入另一堆棧的頂部)我得到6個可能的狀態後:

[[['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'], []]] 

我寫它做到這一點的方法,但我不認爲這是Python的這樣做的方式。這樣做的pythonic方式是什麼?

你可以在下面找到我的代碼。

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 
+0

你讀過[this](http://stackoverflow.com/questions/2853212/all-possible-permutations-of-a-set-of-lists-in-python)嗎? –

回答

3

好像你可以有兩個for循環遍歷該堆棧從彈出這樣做更容易,並推入,分別爲這堆:

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) 

結果:

[['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'], []]