Wednesday, February 18, 2015

Week 6 Object-Oriented-Programming

Week 6 
Object-Oriented Programming Concepts

(Please grade this)

Concepts are of main importance in object-oriented programming. They are the basis on which we can construct our knowledge. During the last 6 weeks we have been talking about different kinds of Abstract Data types, recursion and trees. I would like to briefly summarize some of the key concepts about these topics here:

1.      Abstract Data types
Abstract Data Types, as its name suggests, has at its core abstracting the information and operations by hiding the details. Some examples of abstract data types are stacks, csv files, queues and dictionaries. Each of these examples include data that can be accessed in different ways but they all keep their abstract style.

            Stacks (First in, last out)
·         The first item added is the last one to be removed. Just like a pile of books that depend on the one below to avoid falling.
·         Some of the operations and attributes are:
Push: Add an item on to the top of the stack
Pop: Removed an item from the top of the stack.
Size: The number of elements that the stack contains.
Queues (First in, first out)
·         The first item added is the last one to be removed. Just like people waiting in line.
·         Some of the operations and attributes are:
Push: Add an item at the end of the queue
Pop: Removed an item from the beginning of the queue.
Size: The number of elements that the queue contains.
Stacks and queues are very useful techniques that allow us to store information. The implementation is very similar, but it is necessary to understand how items are added and removed.

Classes
Classes and subclasses also play a role in Object-Oriented Programming in Python. They are just a way to represent information. They include different methods and attributes.

Special Methods
Python comes with these methods for its own classes, but we need to create our own methods for our classes. A clear example of the importance of these methods lies on the method __eq__ without whom we would be comparing just memory addresses.  Some examples of methods are the following:
__init__ Used to initialize variables that are given as parameters when creating an instance of the class.
__str__ Used to give a string version of the class.
__repr__ Used to give a string representation of the class

__eq__ Used to compare attributes among instances of a class

Attributes
Inheritance
In python we have classes and subclasses. Subclasses usually inherit attributes from their parent classes. It is usually done in the following way:

class InheritsFrom(ParentClass):

The methods of a subclass can inherit some attributes, but also add more information and variables. Example:
def __init__(self, subclass_parameter):
ParentClass.__init__(self, class_parameters)
self.new_variable = subclass_parameter

Not implemented errors
We can raise Not Implemented Errors when a method is going to be implemented in a subclass. Example:

raise NotImplementedError(‘need subclass’)

2.      Recursion
Recursion is the process of calling a function within the same function. It is a powerful mean that allows us to repeat a process a considerable number of times. This process combined with list comprehension gives us the ability to create short and neat code. An example of the use of recursion is the following:

def count(L):
            if not(isinstance(L, list)):
                        return 1
else:
            return sum([count(x) for x in L])
Tracing code comes along with recursion and base cases are needed to find the right solution.

3. Trees
Trees include more definitions than the previous topics. Some of these concepts are here:

Tree: A set of nodes.

Nodes: Part of a three that may contain values or labels and are connected with directed edges.

Root: Special node that has no parents.

Path: A sequence of k nodes connected by edges. There is a unique path.

Length of a path: The number of edges on it.

Leaf: A node that has no children

Internal node: Nodes that have one or more children. In other words, nodes that are not leafs.

Subtree: Tree formed by any tree node. A tree is made of subtrees, which include their descendants and the paths leading to them.

Height: one plus the maximum path length in a three. The one is added to account for the imaginary tree in space.

Depth: Height of the tree minus the height of a node.


Arity, branching factor: Maximum number of children for any node. This is basically a number that guides us to create the tree.

Tree example:

class Tree:
def __init__(self, value=None, children=None):
            self.value = value
            self.children = children.copy() if children else []

In the example above, we have created a class tree that will allow us to create trees given its value and children.

Course Interaction: 


Since I know that evaluating peer interaction is difficult, I would like to include some of the links of the blogs and discussions I have taken part in:


http://leopharandcsc.blogspot.ca/2015/02/week-4-lol-lots-of-learning.html?showComment=1425823356912#c9171090264996370596

Saturday, February 7, 2015

Week 5 Tracing recursion

Week 5
Tracing recursion

Recursion seemed like a very abstract topic at first. However, tracing code helps a lot when trying to understand how it works. I would like to use a few lines to wrap my head around this topic.

There is a few techniques and concepts that our professors have been reinforcing on us. Among them:

·    It is important to realize that analyzing a few base cases can give us a good understanding of the whole picture. Don´t forget especial cases such as the empty list.

·    When tracing, we don’t have to trace every single iteration. We can use the behaviour that previous cases had.

·    We may not know how to implement recursive code right away, but we can make an educated guess, trace the code and make corrections.

·    Recursion is the process of calling a function within the same function.

Let’s use these techniques and concepts in the following recursive code.
def count_elements(L):
            if isinstance(L, list):
                        return sum[count_elements(x) for x in L]
            else:
                        return 1

Considering a few Cases:

[] à 0 # Base case Empty list

[1] à sum([count_elements(1)]) à sum([1]) à 1 # Base case List of grade 0

[[1], [2]] à sum([count_elements([1]), count_elements([2])]) à sum([1, 1]) à 2 # We did not traced count_elements([1]) again, since we already did it in the example above.

[[1, [2]], 3, [4]] à [count_elements([1, [2]]), 1, elements([4])] à sum([sum([count_elements(1), count_elements[2]]), 1, 1]]) à sum([sum(1, 1), 1, 1]) à sum(2, 1, 1) à 4

From the second case ([[1], [2]]) we can notice that the aim of our function is to count the number of elements.

Let’s say we did not know what to put in under the else statement. In that case we can still follow the same structure as follows:

[[1], [2]] à sum([count_elements([1]), count_elements([2])]) à sum([sum(count_elements(1)), sum(count_elements(2)])

We would like our answer to be 2, so we infer that we need to return 1.


As we can see, tracing code is definitely useful and it has a direct application when dealing with recursive code.

Sunday, February 1, 2015

Week 4 Classes and subclasses

Week 4
Classes and Subclasses



Computer Science 148 has proved to be a really interesting course so far. Classes and subclasses are a fascinating area of study. However, there is a few points that cause trouble when trying to fully understand how Python works in terms of classes. I would like to tackle some of them here.


Let’s consider the following Python code for which we will assume we have dealt with the __str__ and __eq__ methods:




class FatherPower:
            ’’’A superclass that calculates the power of a number’’’

            def __init__(self):
                        ’’’Initialize a FatherPower class’’’
                        self.result = 0             

            def calculate_power(self, num):
                        ’’’ (int) -> int
Method that calculates the power of a number num
>>> son_class = FatherPower()
>>> son_class.calculate_power(3)
9
’’’
raise NotImplementedError(’need subclass’)
                       
class SonSquare(FatherPower):
’’’ A subclass that calculates the square of a number ’’’

def __init__(self):
                        ’’’Initialize a SonSquare subclass’’’
            FatherPower.__init__(self)

def calculate_power(self, num):
                        ’’’ (int) -> int
Method that calculates the square of a number num
>>> son_class = FatherPower()
>>> son_class.calculate_power(3)
9
’’’
# Sum of the numbers whose squares we calculated within the same instance of SonSquare
self.result = self.result + num
return num ** 2

There is a few things to look at.
1)      First, we notice that SonSquare inherits everything from the supperclass FatherPower. We make it explicit by calling the __init__ method of the supperclass (FatherPower.__init__(self)) and by doing so inheriting the variable self.result that we initialized in the supper class.

2)      Another thing to notice is that the method calculate_power is implemented in the subclass; therefore if we try to call the method directly from the supper classs, we will get a not implemented error.

3)      Super classes and subclasses have slightly different syntax.
Supper class: We write the word class followed by the name of the super class using the CamelCase. We do not include parenthesis after the name of the class.
Syntax: class FatherPower:
Subclass: We write the word class followed by the name of the subclass using the CamelCase. This time, we include the name of the superclass that our subclass inherits from between parentheses.
Syntax: class SonSquare(FatherPower):


I really enjoyed the material taught these weeks and I look forward to programming more on Python.