Sunday, 1 February 2015

My Impression of the First Weeks of CSC148

In these first few weeks of class, we reviewed basic concepts from CSC108 and covered new subjects; the major ones that I believe are: list comprehension and stacks

List Comprehension
List comprehension is a fantastically efficient way to create a list in Python. It encompasses the simplicity, efficiency, and readability one would expect in Python.

For example, if we needed a list of the powers of 2^n, from n = 0 to n = 9, we can construct the list with list comprehension, instead of writing a function for it.

List Comprehension
>>> [2 ** n for n in range(10)]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Function (Doing the same thing)
def powers_of_two(n):
    lst = []
    for x in range(n):
        lst.append(2**x)
    return lst

>>> powers_of_two(10)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Stacks
Stacks are a type of abstract data type in which the last item in is the first item out. An example of this is a Python list, in which when you call append on it, you add the item you want to append to the end of the list. And then when you call pop() on the list, the last item of that list will be removed.

>>> stack = [1, 2, 3]
>>> stack.append(4)
>>> stack
[1, 2, 3, 4]
>>> stack.pop()
4
>>> stack
[1, 2, 3]

Of course, this is only one example of stack. One can even construct a stack as a Python class and then manually implement the methods of pop and push.

No comments:

Post a Comment