Friday, 7 March 2014

Week 8

    This week in CSC148, we focused mainly on linked structures. In the lab, we had to make methods for a LinkedList class including __len__, __setitem__, __delitem__, and insert. The trouble was that the only two helpful methods already built were prepend and decapitate, so we were required to use recursion. This was a bit different than the recursion I have been exposed to so far. We had to kind of count down through the indices i of the LinkedList until 0 was reached, calling the function on i - 1 each time, in order to reach the recursion depth that we wanted to insert at, or set, or delete. Here is the method __getitem__, which demonstrates what I'm trying to say:

  def __getitem__(self: 'LinkedList', ind: int) -> object:
        """Return the item at position ind.
        Raise exception if ind is out-of-range

        >>> lnk = LinkedList(5, LinkedList(7, LinkedList(11, LinkedList())))
        >>> lnk[1]
        7
        """
        if self.empty or ind < 0:
            raise IndexError
        elif ind > 0:
            return self.rest.__getitem__(ind - 1)
        else:
            return self.item

1 comment:

  1. Simple and elegant. Nice work.

    Were you precluded from using iteration? The example above could also have been written iteratively - no? The core logic would have been something like (not carefully checked, and sorry for the syntax, don't know python):

    while(!self.empty && ind > 0)
    {
    self=self.rest;
    ind = ind-1;
    }

    if self.empty raise IndexError
    else return self.item

    ReplyDelete