从物品堆栈,Python限制排序

时间:2013-11-07 07:39:03

标签: python sorting python-3.x stack

我正在研究一个Python问题,让我订购带有一些限制的项目。设置如下:

我有一堆物品给我,以及物品应该在的订单。我被允许对物品进行分类的唯一方法是拉一个物品,然后把它放在堆的顶部。这是唯一允许的方法。我必须按顺序返回我应该提取的项目 - 来自输入 - >以尽可能少的动作建议输出。

正如您在下面的代码中所看到的,我认为最好的方法是简单:从堆栈的底部开始,看看这些项目是否匹配。如果他们这样做,留下他们并移动到下一个项目对(输入对[i],输出[i]。)如果没有,请拉光盘。

这似乎不是最有效的。见下面的例子:

Sample Input Stack- top to bottom
EM, JPE, JB, RAA, CM

Expected New Stack- top to bottom
RAA, JPE, EM, CM, JB

Smallest Moves- order of pulled
CM, EM, JPE, RAA

What my code does- order of pulled
CM, RAA, JPE, EM, RAA, JPE, RAA

这是我的代码:

def takeInput(x):
infile = open(x, 'r')
num_blank = 0
first_stack = []
output_stack = []
stacks = []
for line in infile:
    if line.strip() == "":
        num_blank = 1
    else:
        if num_blank == 0:
            first_stack.append(line.strip())
            #add to start list
        else:
            #add to end list
            output_stack.append(line.strip())
stacks.append(first_stack)
stacks.append(output_stack)
return stacks

def pullDisc(currentStack, pos):
#this function takes a stack & position, pulls the item in that position and puts it on the top
temp = currentStack[pos]
currentStack.pop(pos)
currentStack.insert(0, temp)
return currentStack

def stackTest(startStack, endStack):
moves = []
for i in range(len(startStack)-1, 0, -1):
    while startStack[i] != endStack[i]:
        moves.append(startStack[i])
        pullDisc(startStack, i)
print(startStack, "from stackTest") #pull
return moves


x= input("Please enter the file name: ")
startStack = takeInput(x)[0]
endStack = takeInput(x)[1]
print(startStack, "starting") #pull
print(endStack, "ending goal") #pull
print(stackTest(startStack, endStack), "moves in order")

0 个答案:

没有答案