Python-282个字符
import sys
s=sys.argv[1]
l=s.split()
p=[]
for c in l:
p.append(int(c))
m=sys.maxint
n=0
while(n==(len(p)-1)):
i=x=g=0
for c in p:
if c>g and c<m:
g=c
x=i
i+=1
m=g
x+=1
t=p[:x]
b=p[x:]
t=t[::-1]
p=t+b
a=len(p)-n;
t=p[:a]
b=p[a:]
t=t[::-1]
p=t+b
print p
n+=1
我第一次打高尔夫球 我不抱任何幻想,我会获胜,但是我有很多的乐趣。给所有以一个字符命名的名称肯定会让您感到恐惧,让我告诉您!这是从命令行运行的,示例实现如下:
Python PancakeSort.py "4 2 3 1"
[1, 3, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]
关于此操作的方式,没有什么特别之处或独创性,但是FAQ建议为感兴趣的读者发布一个非高尔夫版本,因此我在下面进行了介绍:
import sys
pancakesStr = sys.argv[1]
pancakesSplit = pancakesStr.split()
pancakesAr = []
for pancake in pancakesSplit:
pancakesAr.append(int(pancake))
smallestSorted = sys.maxint
numSorts = 0
while(numSorts < (len(pancakesAr) - 1)):
i = 0
biggestIndex = 0
biggest = 0
for pancake in pancakesAr:
if ((pancake > biggest) and (pancake < smallestSorted)):
biggest = pancake
biggestIndex = i
i += 1
smallestSorted = biggest #you've found the next biggest to sort; save it off.
biggestIndex += 1 #we want the biggestIndex to be in the top list, so +1.
top = pancakesAr[:biggestIndex]
bottom = pancakesAr[biggestIndex:]
top = top[::-1] #reverse top to move highest unsorted number to first position (flip 1)
pancakesAr = top + bottom #reconstruct stack
alreadySortedIndex = len(pancakesAr) - numSorts;
top = pancakesAr[:alreadySortedIndex]
bottom = pancakesAr[alreadySortedIndex:]
top = top[::-1] #reverse new top to move highest unsorted number to the bottom position on the unsorted list (flip 2)
pancakesAr = top + bottom #reconstruct list
print pancakesAr #print after each flip
numSorts += 1
print "Sort completed in " + str(numSorts) + " flips. Final stack: "
print pancakesAr
我使用的基本算法是问题中链接的Wiki文章中提到的算法:
最简单的煎饼分类算法最多需要2n-3次翻转。在此算法中,这是选择排序的一种变体,我们将尚未排序的最大煎饼移到顶部,然后再翻转一次使其降至最终位置,然后对其余的煎饼重复此操作。