输入
程序的输入将是一个 CD 列表,它们按照它们在起始堆栈中出现的顺序给出(其中输入中首先出现的 CD 位于堆栈顶部)。后面是一个空行,然后是相同 CD 的列表,但按照它们在目标中出现的顺序排列。(一堆CD,后面是空白行和目标列表)
输出
您的程序应该打印出一系列 CD,Johnny 将从堆栈中拉出这些 CD,以便按给定顺序对堆栈进行排序。同样,这一系列动作必须尽可能短。
- 例如,如果堆栈按顺序有 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
我很困惑为什么这会让我超出范围,而且我真的不知道如何以最少的步骤将堆栈列表排序到目标列表。因为它是根据输入而不是按字母顺序对 CD 进行排序的。