Lecture Notes on 21 Feb 2014 Problem: Flip pancakes until they are sorted with the largest at the bottom and the smallest at the top. # finds the index of the local maximum def findMaxIdx (top): size = len(top) idx = 0 maxVal = top[0] for i in range (size): if (top[i] > maxVal): maxVal = top[i] idx = i return idx # flips a sub-stack of pancakes twice so that the local # maximum is at the bottom def flip (a, idx): top = a[:idx] maxIdx = findMaxIdx (top) slice = a[:maxIdx + 1] slice.reverse() top = slice + top[(maxIdx + 1):] top.reverse() for i in range (idx): a[i] = top[i] # Moves the largest pancake to the bottom iteratively def pancake (a): size = len(a) for i in range (size, 0, -1): flip (a, i) def main (): a = [9, 1, 8, 2, 7, 3, 6, 4, 5] print (a) pancake (a) print (a) main()