#!/usr/bin/python # # This program will compute a sequence of flips to # turn a stack of pancakes so that they sit from smallest # to largest (i.e. smallest on top). # # See http://en.wikipedia.org/wiki/Pancake_sorting for # more information on this problem. # # Input will be read from a file, consisting of one # or more sequences of pancakes, each one on a separate line # of the file. It is assumed that the pancake sizes are # given in order (left-to-right) starting from the top of # the stack, and are separated by spaces in the input. # # Output will echo the original sequence of sizes for each # stack and will then indicate the sequence of flips. Flips are # indicated by integers, which represent a pancake who's # position is indicated from the *top* of the stack. # A flip consists of turning over the pancake at some # position i, and all of the pancakes above # it (positions i-1, i-2, ..., 1). # # A "0" indicates that no more flips are necessary for that stack. # # As stated above, the program is designed to read data from # a file (or several files). In other words, to # use this program it should be invoked with a command like # ./pancakes.py pancakes.in # where the file pancakes.in contains the input as described above, # namely each line contains a single stack of pancakes given in # order from top to bottom of the stack, separated by spaces. # Import a library that lets you read from files given as # input to a program, e.g. # ./dostuff.py file1 file2 import fileinput print # process each line in each of the files for line in fileinput.input(): pancakes = line.split() # Split on whitespace # convert the sequence to integers (from strings) pancakes = [int(i) for i in pancakes] n = len(pancakes) if n: # Skip over empty lines in the file. # sorted_list = sorted(pancakes) # only used when testing # print ("\nSorted sequence: ",str(sorted_list).strip('[]')) print str(pancakes).strip('[]'),"\nFlip sequence:", for bottom in range(n-1, 0, -1): max_so_far, index = pancakes[bottom], bottom for i in range(0,bottom): # find the max of # the short stack on top if pancakes[i] > max_so_far: max_so_far, index = pancakes[i], i if index != bottom: # if we have to flip anything... if index != 0: # if we have to flip something # other than the one on top... print index+1, print bottom+1, # then we flip this one # now construct the new stack by taking the relevant # pieces in the right order (after doing either one # or two flips, check that this works..., recall that # "append" adds item to the end of an array) temp = []; # start with empty array for i in range(bottom, index, -1): temp.append(pancakes[i]) for i in range(0,index): temp.append(pancakes[i]) temp.append(pancakes[index]) for i in range(bottom + 1, n): temp.append(pancakes[i]) pancakes = temp[:] # copy array back into pancakes # for the next pass print "0 \n" # we're done, so print out a "0"