以最少的动作排序CD

时间:2013-11-07 04:36:16

标签: python sorting

输入

程序的输入将是一个CD列表,它们按照它们出现在起始堆栈中的顺序给出(输入中首先出现的CD位于堆栈顶部)。接下来是一个空行,然后是相同CD的列表,但按照它们出现在目标中的顺序。 (一堆CD后跟一个空白行和目标列表)

输出

您的程序应打印出一系列CD,Johnny将从堆栈中取出,以便按给定的顺序对堆栈进行排序。同样,这一系列的动作必须尽可能短

  • 例如,如果堆栈按顺序包含CD A,B和C(顶部有A),我可以选择先拉出B.这样做然后将堆栈的顺序更改为B,A,和C.

示例输入1

Eamon McGrath - Peace Maker
Joel Plaskett Emergency - Ashtray Rock
Jimmy Buffett - The Best of Jimmy Buffett
Rural Alberta Advantage - Hometowns
Chuck Mangione - Feels So Good

Rural Alberta Advantage - Hometowns                           
Joel Plaskett Emergency - Ashtray Rock
Eamon McGrath - Peace Maker
Chuck Mangione - Feels So Good
Jimmy Buffett - The Best of Jimmy Buffett

样本输入1的输出

Chuck Mangione - Feels So Good
Eamon McGrath - Peace Maker
Joel Plaskett Emergency - Ashtray Rock
Rural Alberta Advantage - Hometowns

这是我的代码:

import random
lst=[]

while True:
     try: 
          strline = input()
          if len(strline)>0:
               lst.append(strline)
          if strline == "END":
               lst.pop()
               break
     except:
          break


#print(len(lst))  #this will print size 10  for sample input #1
x=len(lst)//2
stacklist=lst[:x]  #print(lst[:x])  the stack of CDs that is not ordered
goal=lst[x:]       #print(lst[x:])  this will print the goal

index_lst=random.randrange(len(lst)-1)
index_stacklist=random.randrange(1,(len(lst)//2))

steps=[]
while stacklist != goal:
     stacklist.insert(0,stacklist.pop(index_stacklist)) #pick a CD and put it on the top
     steps.append(stacklist.pop(index_stacklist)) #append the move to a list

print(steps) # print the steps out

我很困惑为什么这会让我超出范围,  而且我真的不知道如何在最少的步骤中将stacklist排序到目标列表。 因为根据输入,它不按字母顺序排列,而是按顺序排序。

0 个答案:

没有答案