2013年11月30日星期六

week #2 ----Stacks

In the second week, I learn Stacks ADT, which include the following operations:

  • __init__ (Initialize a new empty stack)
  • push (add a new item to the stack
  • pop (remove and return an item from the stack. the item that is returned is always the last one that was added)
  • is_empty (check whether the stack is empty)
The data structure is LIFO called "Last in, First out"

Classes and objects --- the basics

The first week I study the basics of classes and objects. First of all is Object-oriented programming. It is not only the data type of a data structure, but also the types of functions that can be applied to the data structure. Second I learn how to define a new class as follow:
           class Point:
    """ Point class represents and manipulates x,y coords. """

    def __init__(self):
        """ Create a new point at the origin """
        self.x = 0
        self.y = 0
Third I know what are build-in objects:
         >>>w1 = "word"
         >>>w2 = "swords"[1: ]
         >>>w1 is w2
         False
         >>>import turtle
         >>> t = turtle.Turtle()
         >>>t.pos()
         (0.00, 0.00)
Also I learn how to add other methods to class. A method behaves like a function but it is invoked on a specific instance.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Point:
    """ Create a new Point, at coordinates x, y """

    def __init__(self, x=0, y=0):
        """ Create a new point at x, y """
        self.x = x
        self.y = y

    def distance_from_origin(self):
        """ Compute my distance from the origin """
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5