Lecture Notes on 18 Feb 2013 # Flip pancakes to get them in sorted order # Find the index of the max value in a sub-list 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 # Flip pancakes to get one of the pancakes in # its right place def flip (a, idx): # Get the stack of pancakes form the top top = a[:idx] # Find where the biggest pancake is in # that portion maxIdx = findMaxIdx (top) # Get slice that has the biggest pancake # at the bottom slice = a[:maxIdx + 1] # Flip so that the biggest is on the top slice.reverse() # Now add the flipped portion and the # unflipped portion top = slice + top[(maxIdx + 1):] # Flip again so that the biggest is # in the right position top.reverse() # Copy the changes back to the original array for i in range (idx): a[i] = top[i] 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()