Friday, March 7, 2014

Week 8: Lab on LinkedLists

This week's lab is a follow-up to last week's task. We did the part called implement list  (sort of). A similar recursion was used for LinkedList traversal. Such was mentioned in last week's blog. At some point after our lab on Tuesday, Dan added the extra section for the lab.

I did copy_ll:

  def copy_ll(self: 'LinkedList') -> 'LinkedList':
    """Return a copy of LinkedList.
    >>> lnk = LinkedList(5)
    >>> lnk.prepend(7)
    >>> lnk2 = lnk.copy_ll()
    >>> lnk is lnk2
    False
    >>> lnk == lnk2
    True
    >>> lnk.prepend(11)
    >>> lnk == lnk2
    False
    """
    if self.empty:
      return LinkedList()
    return LinkedList(self.head, self.rest.copy_ll())

I tested the docstring but it failed on the first lnk == lnk2, so I ran it manually and constantly printed lnk and lnk2 to compare them:

>>> lnk = LinkedList(5)
>>> lnk.prepend(7)
>>> lnk2 = lnk.copy_ll()
>>> lnk
LinkedList(6, LinkedList(7, LinkedList(5, LinkedList())))
>>> lnk2
LinkedList(6, LinkedList(7, LinkedList(5, LinkedList())))

They're the same, so I suspected the lack of __eq__ method is to blame. I proceeded to implement __eq__.

  def __eq__(self, other) -> bool:
    if self.empty and other.empty:
      return True
    elif self.empty or other.empty:
      return False
    return self.head == other.head and self.rest == other.rest

Then it worked. That was too much effort because I kept fixing copy_ll to pass the docstring test, and was quite late to realize the lack of __eq__ was the culprit.

Tired now. See you next week :P

No comments:

Post a Comment