Program: Algorithms_6_pancake.py
#Algorithms and Computational Thinking #Program for Example 6, arranging te pancakes # from __future__ import print_function def printCakes(cakes): total = len(cakes) for cake in cakes: for i in range(total-cake): print(' ',end='') for i in range(cake): print('-',end='') print(cake,end='') for i in range(cake): print('-',end='') print() printLine() raw_input('Press any key to continue...') printLine() def flipCakes(cakes,position): top_cakes = cakes[0:position+1] top_cakes.reverse() bottom_cakes = cakes[position+1:] return top_cakes+bottom_cakes def printLine(): print('.....................') def arrangeCakes(cakes): largest = len(cakes) count = 0 while largest != 1: if(largest != (cakes.index(largest)+1)): #if the next largest pancake to position is not on the top, flip to get it there if(cakes.index(largest)!= 0): cakes = flipCakes(cakes, cakes.index(largest)) count += 1 print('Step',count) printLine() printCakes(cakes) #once the next largest pancake to position is one top, flip cakes = flipCakes(cakes,largest -1) count += 1 largest -= 1 print('Step',count) printLine() printCakes(cakes) else: largest -= 1 return count #Example Data my_cakes = [3,6,2,1,7,5,4] #Print original pancakes print('Original') printLine() printCakes(my_cakes) count = arrangeCakes(my_cakes) print('Total Steps:',count)
Output
..................... Step 8 ..................... -1- --2-- ---3--- ----4---- -----5----- ------6------ -------7------- ..................... Press any key to continue... ..................... Total Steps: 8