Pythonic方式来洗牌堆栈

时间:2015-10-05 18:11:30

标签: python shuffle

我想在任意数量的堆栈中混乱元素。例如,如果我有3个堆栈,并且堆栈的元素如下 [ ["A", "C"] , ["B" , "D" ] ["E"] ]

在洗牌之后(从一个堆栈的顶部移除并插入另一个堆栈的顶部)我得到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'], []]]

我已经写了一个方法来做到这一点,但我不认为这是pythonic方式。这样做的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

1 个答案:

答案 0 :(得分: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'], []]