从项目堆栈限制排序,Python

2024-06-17 13:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个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")

Tags: toinstacklinecmprintemappend