Homework Solution

Recursion

Problems to be Submitted (18 points)

  1. (6 points)

    def __le__(self,other):
        if self._isEmpty():
            return True          # empty list is less than or equal to anything
        elif other._isEmpty():
            return False         # cannot otherwise be less than or equal to an empty list
        else:
    	# both lists are non empty; compare the heads
    	if self._head < other._head:
    	    return True
    	elif self._head > other._head
    	    return False
    	else:
    	    # heads are the same; revert to rest
    	    return self._rest <= other._rest
    

  2. (6 points)

    def index(self, value, start=0):
      if self._isEmpty():
        raise ValueError('OurList.index(x): x not in list')
      elif start == 0 and self._head == value:
        return 0
      else:
        return 1 + self._rest.index(value, max(start-1,0))
    

  3. (6 points)

    def binary(n):
      answer = str(n % 2)   # rightmost bit, for now
      if n >= 2:
        answer = binary(n // 2) + answer
      return answer
    


Extra Credit

  1. (2 points)

    def __getslice__(self,i,j):
        """
        Returns new list representing self[i:j]
    
        Assumes that i and j are non-negative.
        """
        if self._isEmpty() or i >= j:
            return OurList()    # a new empty list
        elif i > 0:
            return self.rest.__getslice__(i-1,j-1)
        else:
            result = OurList()
            result.head = self.head
            result.rest = self.rest.__getslice__(0,j-1)
            return result
    


Last modified: Monday, 02 May 2011