Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自项目堆栈的受限排序,Python_Python_Sorting_Python 3.x_Stack - Fatal编程技术网

来自项目堆栈的受限排序,Python

来自项目堆栈的受限排序,Python,python,sorting,python-3.x,stack,Python,Sorting,Python 3.x,Stack,我正在处理一个Python问题,该问题使我对项目进行排序时有一些限制。设置如下所示: 我有一堆给我的物品,以及这些物品的顺序。我被允许对项目进行排序的唯一方法是拉动一个项目,并将其放在堆的顶部。这是唯一允许的方法。我必须返回我应该提取的项目,以便以尽可能少的移动从输入-->建议输出返回 正如您在下面的代码中所看到的,我认为实现这一点的最佳方法很简单:从堆栈的底部开始,查看项目是否匹配它们应该位于的位置。如果有,则将其保留并移动到下一个项目对(输入[i],输出[i])。如果没有,则拉动光盘 这似乎

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

这是家庭作业问题吗?是的,2013年;);我从不看日期。。。