Tuesday, April 23, 2013

All Sorts of Pancakes

Python has a handy built-in method for sorting objects in a list intuitively called sort(). Although this functionality is great, there are times that we need to use a different type of sorting to solve certain problems. Last week, we interns were given exercises to familiarize ourselves with the Python programming language. One of the exercises given was to sort a list of numbers using a technique similar to flipping a stack of pancakes (hence known as the pancake sort). The goal is to arrange the list by reversing one group of pancakes at a time.
Mmmmm... pancakes...
Mmmmm... pancakes... ♥

By utilizing what we have learned from our discussions, I used one of the built-in data types in Python called the list to solve the pancake problem. A list is similar to an array in other programming languages, but is more advanced and versatile. It can hold different types of values such as strings, objects, and even lists in itself.

Some of the available methods for a list we can use for the pancake sort includes:
  • list[n:m]: returns a subset of the list starting from n to m
  • list.index(n, i): returns the index of the item n in a list starting from i
  • max(list): returns the largest item in a list
  • len(list): returns the total length or number of items in a list
  • reversed(list): returns a reversed copy of the list
Now suppose you have a tower of pancakes with different sizes. The process of the pancake sort goes like this:
  1. Find the largest pancake m in the unordered part of the list
  2. Flip the group of pancakes from the topmost pancake to pancake m so that m will be at the top
  3. Flip the unordered part again so that m will be at the bottom of the list
  4. Repeat until all pancakes are in the right place
By using the available methods, the final product will (or may) look similar to this:
    for i in range(len(pancakes)):
        largest = pancakes.index(max(pancakes[i:len(pancakes)]), i)
        if largest != i:
            if largest != len(pancakes):
                pancakes[largest:len(pancakes)] = reversed(pancakes[largest:len(pancakes)])
            pancakes[i:len(pancakes)] = reversed(pancakes[i:len(pancakes)])
And that is it, pancit. Place it in a function and pass it a list and it will be sorted pancake-style!

Last few words I want to say: though I may not look like it, I am still a guy who loves simplicity and beauty. And that my friends is why I love pancakesPython. :)

No comments:

Post a Comment