1

我正在处理一个 Python 问题,该问题让我订购有一些限制的物品。设置是这样的:

我有一堆物品给我,以及物品的顺序。我被允许对物品进行分类的唯一方法是拉出一个物品,并将其放在堆的顶部。这是唯一允许的方法。我必须返回我应该拉的项目,以便从输入 - >建议的输出中尽可能少的移动。

正如您在下面的代码中看到的那样,我认为最好的方法很简单:从堆栈的底部开始,查看项目是否匹配它们应该在的位置。如果有,离开它们并移动到下一个项目对(对是 input[i],output[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")
4

0 回答 0