Tuesday, February 10, 2015

Abstract Data Types: Stacks and Queues

        Python contains many base data types such as lists, strings, integers, and floats. They are generally universal, but sometimes a modified or completely new data type is needed for a certain scenario. For example, in the case of a queue for a restaurant, a list is a perfectly viable way to sequence the numbers while being mutable, however the proper way to modify the list would be that only the front object can be removed, and objects are added to the queue at the back. These restrictions allow for this queue data type to exist as a modified list. In the case of a stack, one may want to represent a sequence of layers placed upon one another. Once again a list is optimal for representing the sequence, however you would only want to be able to add to, and remove from, the last item in the sequence (removing the bottom/ first totem in a totem pole would be impractical, and the pole would collapse).

Monday, February 2, 2015

Recursion


         Many functions act on list objects to produce values asuch as the max value, sum of all values, etc. However when the list has a list within it, functions like sum must be called on the inner list to produce a value computable along with the other values. For example, sum([5, [2, 3], 5]) would result in an error due to the addition of an int and list. what would need to first happen is that sum([2, 3]) is first computed, then sum([5, sum([2, 3]), 5]). We can utilize a for loop in order to cycle through every object in the lowest depth list. If the current object is not a list, return/ process accordingly. However if the current object is a list, run the same for loop on the inner list.

def summer(L):
    if isinstance(list, L):
        return sum([summer(x) for x in L])
    else:
        return L

 On the list [5, [2, 3], 5], the objects of the outer list 5, [2, 3], and 5 will be run through the function. the 5 and 5 are not lists, and will be returned into the outer list, and the [2, 3] will be acted on by summer (summer([2, 3])). On a list with a depth of one the function will simply sum the values as all objects are returned in a list, and are summed. Thus summer([2, 3]) -> sum([summer(2), summer(3)]) -> sum([2, 3]) -> 5. This value is then returned into the outer list. sum(summer(x) for x in [5, [2, 3], 5]) -> sum([summer(5), summer([2, 3]), summer(5)]) -> sum([5, 5, 5]) -> 15. As lists gain a larger depth, the summer function is called more times as it iterates over every internal list.